Typescript 是否可以从泛型类型自动生成类属性?
TypeScript中是否有任何方法可以从泛型类型生成具有以下属性的类:Typescript 是否可以从泛型类型自动生成类属性?,typescript,typescript-generics,Typescript,Typescript Generics,TypeScript中是否有任何方法可以从泛型类型生成具有以下属性的类: class-SomeClass{ //在这里读T的道具? } 界面道具{ a:数字; b:布尔型; } const obj=新类; //因此,现在obj.a和obj.b都可以在Props界面中使用正确的类型自动完成 接口道具2{ 一些:弦; 其他:数字; 道具:布尔; } const obj2=新的SomeClass; //现在obj2只能使用Props2中的三个道具 我不想添加类似的内容 class-SomeClass
class-SomeClass{
//在这里读T的道具?
}
界面道具{
a:数字;
b:布尔型;
}
const obj=新类;
//因此,现在obj.a和obj.b都可以在Props界面中使用正确的类型自动完成
接口道具2{
一些:弦;
其他:数字;
道具:布尔;
}
const obj2=新的SomeClass;
//现在obj2只能使用Props2中的三个道具
我不想添加类似的内容
class-SomeClass{
[道具:字符串]:任何
}
因为它只允许在那里分配任何属性,并且我希望有来自泛型类型的固定列表,映射类型不能在类中使用。但是,根据这里的答案:,您可以创建一个函数来创建一个对象,该对象的属性定义与如下接口匹配:
interface Props {
a: number;
b: boolean;
}
function build<T>(value?: T): T {
return Object.assign({}, value);
}
const obj = build<Props>();
// obj contains typed a and b properties
// Or, pass in default values
// const obj = build<Props>({ a: 2, b: false });
界面道具{
a:数字;
b:布尔型;
}
功能构建(值?:T):T{
返回Object.assign({},value);
}
const obj=build();
//obj包含类型化的a和b属性
//或者,传入默认值
//const obj=build({a:2,b:false});
您在这里寻找的是比标准继承更接近于标准继承的东西。但是接口X的通用混合扩展了T
的多样性
您可以创建一个名为SomeClass
的对象和一个名为SomeClass
的泛型类型,通过一些类型断言,它们可以以这种方式使用,但您确实会遇到一些限制。我可以这样做:
class _SomeClass<T> {
constructor(t: T) {
Object.assign(this, t);
}
// inside here we don't know about properties of T, though
// so you'll have to do assertions
get<K extends keyof T>(k: K): T[K] {
return (this as any as T)[k]; // assertion
}
}
type SomeClass<T> = T & _SomeClass<T>;
const SomeClass = _SomeClass as new <T>(t: T) => SomeClass<T>;
这些程序使用您期望的IntelliSense进行编译
当然,还有一些限制。TypeScript实际上只允许您扩展静态已知键名的类。因此,如果您需要SomeClass
的泛型子类,那么您就不走运了:
class Nope<T> extends SomeClass<T> { // error!
/* Base constructor return type 'SomeClass<T>' is
not an object type or intersection of object types
with statically known members. */
}
好吧,希望这会有帮助;祝你好运
class Nope<T> extends SomeClass<T> { // error!
/* Base constructor return type 'SomeClass<T>' is
not an object type or intersection of object types
with statically known members. */
}
class Okay extends SomeClass<Props> {
}