Skip to content

Problems with computed property must be of type 'string', 'number', 'symbol', or 'any'. #17587

Closed
@remojansen

Description

@remojansen

I'm having problems with the restriction:

A computed property name must be of type 'string', 'number', 'symbol', or 'any'.

And the following function:

const selectWhere = <T, W extends keyof T, S extends keyof T>(where: W, select: S) =>
    (entities: T[], value: T[W]) =>
        entities.filter(e => e[where] === value)
                .map(e => ({
                    [select]: e[select] // Error
                }));

The functioin shoud allow me to filter an awway by a property and select some attributes:

interface User {
    surname: string;
    age: number;
}

const selectSurnameWhereAge = selectWhere<User, "age", "surname">("age", "surname");

const users = [
    { surname: "Smith", age: 28 },
    { surname: "Johnson", age: 28 },
    { surname: "Williams", age: 14 }
];

let result = selectSurnameWhereAge(users, 28);

result[0].surname; // "Smith"
result[0].age; // Error
result[1].surname; // "Johnson"
result[2].age; // Error

I have a work around but it is very verbose:

const selectWhere = <T, W extends keyof T, S extends keyof T>(where: W, select: S) =>
    (entities: T[], value: T[W]) =>
        entities.filter(e => e[where] === value)
                .map(e => {
                    let obj = {};
                    Object.keys(e).forEach((k) => {
                        if (k === select) {
                            obj[k] = e[k];
                        }
                    })
                    return obj as Pick<T, S>;
                });

Reproduce it at the Playground.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions