让我们假设有一个模型类,如:
export abstract class Target {
id!: number;
name!: string;
}
export class Target1 extends Target {
name = 'target1';
id: number;
kind: string;
constructor(id: number, kind: string) {
super();
this.id = id;
this.kind = kind;
}
static getForm(){
return new FormGroup({...});
}
}
export class Target2 extends Target {
name = 'target2';
id: number;
address: string;
constructor(id: number, address: string) {
super();
this.id = id;
this.address = address;
}
static getForm(){
return new FormGroup({...});
}
}
....
export class TargetN extends Target {}
type Measure = {
type: string;
target: any; // Here is what I need to correct the type
}
const measures: Measure[] = [
{ type: 'measure1', target: Target1},
{ type: 'measure2', target: Target2},
...
{ type: 'measureN', target: TargetN},
];
在表单中,我允许用户根据用户选择的measures.type
的情况输入address
或kind
,然后我将创建一个新的target
,如下所示:
const inputValue = 'http://localhost:3000';
const selectedType = measures[0].type;
const measure = measures.find(m => m.type === selectedType)!;
const target = new measure.target(1, inputValue);
const form = measure.target.getForm();
console.log(target.kind); //
...
一切都很好。但让我恼火的是,我不知道如何将正确的类型放在Measure -> target
而不是any
:
type Measure = {
type: string;
target: any; // ???
}
如果我给它一个Target
类型,如下所示:
type Measure = {
type: string;
target: Target;
}
然后我会得到错误
Did you mean to use 'new' with this expression?
如果我给它typeof
,就像下面这样:
type Measure = {
type: string;
target: typeof Target;
}
然后我会得到错误
Type 'typeof Target1' is not assignable to type 'typeof Target'.
如何用另一种特异性类型替换靶点中的any
型?
如果我使用ThisType,它看起来不错
type Measure = {
type: string;
target: ThisType<Target>;
}
但CCD_ 10在CCD_ 11中会抛出错误
Property 'getForm' does not exist on type 'ThisType<Target>'.
我还尝试了Required,如下所示:
type RequiredTarget = Required<typeof Target>;
type Measure = {
type: string;
target: RequiredTarget;
}
但它也不起作用。
我很感激你的帮助。
我会用以下方式来处理这个问题:
type S = string;
type I = number;
interface IY {
type?: string;
target?: S | I;
}
type Y = IY
const U: Y = { type: "U", target: "1" }
const V: Y = { type: "V", target: 2 }
const X: Y = {}