gpt4 book ai didi

TypeScript - 仅提取接口(interface)成员 - 可能吗?

转载 作者:搜寻专家 更新时间:2023-10-30 20:34:07 48 4
gpt4 key购买 nike

有没有办法从属于接口(interface)的对象中动态提取成员(即不再明确指定它们),如下所示:

let subset = { ...someObject as ISpecific }; 

目前我得到了 someObject 碰巧拥有的所有成员。所以传播运算符在这里不起作用。有没有办法做到这一点?

示例:

interface ISpecific { A: string; B: string; }
class Extended implements ISpecific { public A: string = '1'; public B: string = '2'; public C: string = '3'; }

let someObject = new Extended();
let subset = { ...someObject as ISpecific };
console.log(subset); // -> { A, B, C } but want { A, B }

TypeScript 转换只是对编译器的提示,而不是运行时的真正转换。

最佳答案

由于 typescript 接口(interface)在运行时不存在,我们不能使用它们来指导任何运行时行为,只能用于编译时类型检查。然而,我们可以创建一个与接口(interface)具有相同属性的对象(例如,具有类型为 true 的所有属性以简化初始化)并使编译器在该对象具有更多或更少的属性时触发错误字段然后是界面。我们可以使用此对象作为我们提取哪些属性的指南:

function extract<T>(properties: Record<keyof T, true>){
return function<TActual extends T>(value: TActual){
let result = {} as T;
for (const property of Object.keys(properties) as Array<keyof T>) {
result[property] = value[property];
}
return result;
}
}

interface ISpecific { A: string; B: string; }
const extractISpecific = extract<ISpecific>({
// This object literal is guaranteed by the compiler to have no more and no less properties then ISpecific
A: true,
B: true
})
class Extended implements ISpecific { public A: string = '1'; public B: string = '2'; public C: string = '3'; }

let someObject = new Extended();
let subset = extractISpecific(someObject);

关于TypeScript - 仅提取接口(interface)成员 - 可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50839597/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com