Typescript-属性将自身作为参数的接口
我有一个类型,其中一个属性是将该类型作为参数的类Typescript-属性将自身作为参数的接口,typescript,Typescript,我有一个类型,其中一个属性是将该类型作为参数的类 interface Type<P extends {}> { name: string; props: P; field: new(type: Type<P>) => { ... }; } // Define some Types interface AllTypes { Foo: Type<{}>; Bar: Type<{ foo: string; bar:
interface Type<P extends {}> {
name: string;
props: P;
field: new(type: Type<P>) => { ... };
}
// Define some Types
interface AllTypes {
Foo: Type<{}>;
Bar: Type<{
foo: string;
bar: number
}>
}
type SomeType = AllTypes[keyof AllTypes];
将Type.field
更改为new(Type:SomeType)=>…
将解决此错误,但会进一步产生错误:
class Field<T extends SomeType> {
type: T;
constructor(type: T) {
this.type = type;
}
}
declare class FooField extends Field<AllTypes['Foo']> {}
declare class BarField extends Field<AllTypes['Bar']> {}
const fields: SomeType[] = [
{
name: 'foo',
props: {},
field: FooField,
},
{
name: 'bar',
props: { // This error is expected and desired
foo: 0,
bar: 'hi',
},
field: BarField, // Error
},
];
类字段{
类型:T;
建造师(类型:T){
this.type=type;
}
}
声明类FooField扩展字段{}
声明类BarField扩展字段{}
常量字段:SomeType[]=[
{
名称:“foo”,
道具:{},
字段:FooField,
},
{
名称:'酒吧',
道具:{//此错误是预期的,也是预期的
傅:0,,
酒吧:嗨,
},
字段:BarField,//错误
},
];
我想这就是你想要的:
interface Type<P extends {}> {
name: string;
props: P;
field: new<T extends Type<any>>(type: T) => { };
}
接口类型{
名称:字符串;
道具:P;
字段:new(类型:T)=>{};
}
interface Type<P extends {}> {
name: string;
props: P;
field: new<T extends Type<any>>(type: T) => { };
}