I am currently working on implementing a function that selects specific properties of an object. Here is the current function:
const project = function<T>(object: T, projection: Projection<T>): Partial<T> {
throw new Error("not implemented yet");
};
The Projection<T>
type is defined as:
type Projection<T> = {
[key in keyof T]?: 1 | 0
};
This functionality is similar to MongoDB's project
operation, where a user can specify which properties to pick from the object by passing an object like {_id: 1, name: 1}
.
However, when attempting to create another function that allows users to select only one property to project, I encountered this 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'm puzzled as to why this error occurred, considering that the type of propertyName
should be a key of T
, and Projection<T>
allows keys from T
. Any suggestions on how to resolve this issue?