Shaun Xu
Shaun Xu

Reputation: 4656

Failed to set object property value when it is defined as [key in keyof T]

I'm trying to implement a function to pick properties of an object. the function was

const project = function<T>(object: T, projection: Projection<T>): Partial<T> {
    throw new Error("not implemented yet");
};

The definition of Projection<T> was

type Projection<T> = {
    [key in keyof T]?: 1 | 0
};

Something like MongoDB project operation. User can pass {_id: 1, name: 1} so that we picked id and name from the object.

When I tried to create another function which allows user to specify one property to project, I got the following error.

const project_one_property = function<T, K extends keyof T>(object: T, propertyName: K): Partial<T> {
    //    Type '{ [x: string]: number } is not assignable to type 'Projection<T>'.
    //    vvvvvvvvvv
    const projection: Projection<T> = {
        [propertyName]: 1
    };
    return project(object, projection);
};

I don't know why this error occurred since the type of propertyName should be key of T and Projection<T> allows keys from the key of T.

What I can do to make this function works.

Upvotes: 1

Views: 89

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249676

The compiler appears to infer { [x: string]: number; } for any object literal that uses a computed property name. You could use a type assertion to any on the object literal. Or you could initialize the value in two steps:

const projection: Projection<T> = {};
projection[propertyName] = 1;

Upvotes: 1

Related Questions