For example, a DB Schema (Mongoose) like this:
@Schema()
class Schema {
id: string;
version: number;
@Prop({
type: String
})
name: string;
somefiled: string;
deleted: boolean;
created_at: Date;
updated_at: Date;
}
A Create Request Dto maybe like this:
class ReqDto {
name: string;
somefiled: string;
}
// other column fields may be generated
// so that we do not pass them from the request
A Get Request Response Dto maybe like this:
class ResDto {
name: string;
somefiled: string;
// some transformed fields
somefiled2: string;
created_at: Date;
updated_at: Date;
}
// some column fields may be hidden
I want to make ReqDto and ResDto a bit like this:
class ReqDto {
// Pick fields from the schema Class (or Interface)
[key: Pick<Schema, 'name', 'somefiled'>];
}
class ResDto {
// Pick fields from the schema Class (or Interface)
[key: Pick<Schema, 'name', 'somefiled', 'created_at', 'updated_at'>];
// some other fields
somefiled2: string;
}
however, i have no idea how to realize it.
Here's my errored demo codes:
interface Schema {
id: string;
version: number;
created_at: Date;
updated_at: Date;
}
// OK
type Demo1 = {
[P in keyof Schema]: Schema[P];
};
// error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
// error TS7008: Member '[P in keyof' implicitly has an 'any' type.
// error TS2304: Cannot find name 'P'.
// error TS2304: Cannot find name 'keyof'.
// error TS2693: 'Schema' only refers to a type, but is being used as a value here.
// error TS1005: ']' expected.
// error TS1005: ';' expected.
// error TS1128: Declaration or statement expected.
interface Demo2 {
[P in keyof Schema]: Schema[P];
};
// error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
// error TS7008: Member '[P in keyof' implicitly has an 'any' type.
// error TS2304: Cannot find name 'P'.
// error TS2304: Cannot find name 'keyof'.
// error TS7008: Member 'Schema' implicitly has an 'any' type.
// error TS2300: Duplicate identifier 'Schema'.
// error TS7008: Member '[P]' implicitly has an 'any' type.
// error TS1005: ']' expected.
// error TS1005: ';' expected.
// error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
// error TS1005: ';' expected.
class Demo3 {
[P in keyof Schema]: Schema[P];
};
// error TS1337: An index signature parameter type cannot be a union type. Consider using a mapped object type instead.
interface Demo4 {
[P: keyof Schema]: Schema[P];
}
// error TS1337: An index signature parameter type cannot be a union type. Consider using a mapped object type instead.
class Demo5 {
[P: keyof Schema]: Schema[P];
}