簡體   English   中英

typescript:如何注釋類型是 class(而不是 class 實例)?

[英]typescript: How to annotate a type that's a class (instead of a class instance)?

假設有一個 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},
];

在表單中,我允許用戶根據用戶選擇的情況輸入addresskind 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); // 
...

一切正常。 但令我煩惱的是,我不知道如何將正確的類型放在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>;
}

但是Target1 or Target2中的static method會拋出錯誤

Property 'getForm' does not exist on type 'ThisType<Target>'.

我還嘗試了如下必需的:

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 = {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM