[英]typescript: How to annotate a type that's a class (instead of a class instance)?
Let's assume there is a model class like:假设有一个 model class 像:
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},
];
In the form, I allow user input address
or kind
based on situation user selected measures.type
then I will instance a new target
as bellow:在表单中,我允许用户根据用户选择的情况输入address
或kind
measures.type
然后我将实例化一个新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); //
...
Everything is working fine.一切正常。 But which annoys me is that I don't know how to put the correct type at Measure -> target
instead of any
:但令我烦恼的是,我不知道如何将正确的类型放在Measure -> target
而不是any
:
type Measure = {
type: string;
target: any; // ???
}
If I give it a type Target
like bellow:如果我给它一个Target
类型,如下所示:
type Measure = {
type: string;
target: Target;
}
then I will get the error然后我会得到错误
Did you mean to use 'new' with this expression?
And, if I give it typeof
like bellow:而且,如果我给它typeof
如下所示:
type Measure = {
type: string;
target: typeof Target;
}
then I will get the error然后我会得到错误
Type 'typeof Target1' is not assignable to type 'typeof Target'.
How can I replace type any
in target with another specificity type?如何将目标中的any
类型替换为另一种特异性类型?
If I use ThisType it looks good如果我使用ThisType它看起来不错
type Measure = {
type: string;
target: ThisType<Target>;
}
but the static method
inside Target1 or Target2
it will throw error但是Target1 or Target2
中的static method
会抛出错误
Property 'getForm' does not exist on type 'ThisType<Target>'.
I also tried with Required like below:我还尝试了如下必需的:
type RequiredTarget = Required<typeof Target>;
type Measure = {
type: string;
target: RequiredTarget;
}
but it's not working too.但它也不起作用。
I appreciate your help with that.我很感激你的帮助。
I would approach this with the following manner:我将通过以下方式解决此问题:
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 = {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.