首页 > 解决方案 > 打字稿:如何注释一个类(而不是类实例)的类型?

问题描述

假设有一个模型类,如:

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>;
}

static method里面Target1 or Target2会抛出错误

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

我还尝试了如下必需的:

type RequiredTarget = Required<typeof Target>;
type Measure = {
    type: string;
    target: RequiredTarget;
}

但它也不起作用。

我很感激你的帮助。

标签: javascriptreactjsangulartypescript

解决方案


我将通过以下方式解决此问题:

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

推荐阅读