很难 Select 一个适当的总结,所以让我来解释一下我的问题.我有一堆类,每个类都有一个toJSON方法,可以将类转换为它的JSON表示.我想 for each 方法添加一个新的可选参数,它允许我只返回类属性的一个子集,而不是所有属性.该方法的返回类型应该根据开发人员 Select 的属性进行相应的更改.
我想使此类型安全,但我还没有达到完全满足我的需要的程度.以下是缺少的简短示例:
interface IUser {
id: string;
name: string;
age: number;
}
const fullUser = user.toJson(); // full "IUser"
const truncatedUser = user.toJson({ attributes: ['name'] }); // Pick<IUser, 'name'>
fullUser.id // works
truncatedUser.id // should throw an error, but tsc compiles
完整的例子,我已经实现了到目前为止.
// Using the generic here, because I want to pass interface IUser, or IABC, or IDEF etc
interface IJSONExportOptions<Type> {
/** A list of object properties that are included in the the resulting JSON. */
attributes?: (keyof Type)[];
}
interface IUser {
id: string;
name: string;
age: number;
}
class User {
private id: string;
private name: string;
private age: number;
constructor() {
this.id = '1';
this.name = 'Jon Doe';
this.age = 20;
}
toJSON(opts?: IJSONExportOptions<IUser>) {
const fullObj: IUser = {
id: this.id,
name: this.name,
age: this.age,
};
if (!opts?.attributes?.length) {
return fullObj as Pick<IUser, keyof IUser>;
}
const truncatedUser: Partial<Pick<IUser, keyof IUser>> = {};
for (const key of opts?.attributes) {
const val = fullObj[key];
truncatedUser[key] = val;
}
return truncatedUser as Pick<IUser, keyof IUser>;
}
}
const user = new User()
const fullUser = user.toJSON();
console.log(fullUser.age);
const truncatedUser = user.toJSON({ attributes: ['name'] });
console.log(truncatedUser.age); // I want that tsc throws an error here, but also that my IDE does not provide autocomplete for "undefined" properties
如果这很重要,代码使用typescript 4.4.3(升级是一个选项).
如有任何帮助,我们不胜感激.