打字稿:定义类集合的类型

m2c

我不知道如何在打字稿中定义类集合的类型:

当我编译以下代码时,出现错误:

    class Wall{
        brick: string;

        constructor(){
            this.brick = "jolies briques oranges";
        }

        // Wall methods ...
    }

class Critter {
    CritterProperty1: string[];
    CritterProperty2: string;

    constructor() {
        this.CritterProperty1 = "n ne e se s so o no".split(" ");        
    }

    // Critter methods ...
}

type legendObjectType = Critter | Wall;

interface Ilegend {
    [k: string]: legendObjectType; 
}

// i've got an issue to define the type of 'theLegend' Object
let theLegend: Ilegend = {
    "X": Wall,
    "o": Critter
}

错误 TS2322: 类型 '{"X": typeof Wall; “o”:小动物的类型;}' 不可分配给类型 'Ilegend'。

虽然我可以编译它,如果“类墙”是空的。

有谁知道如何定义这样一个类的集合的类型?

let theLegend = { "X": Wall, "o": Critter }

(这是eloquent javascript第 7 章的一个例子,而不是我尝试用打字稿转录)

编辑

我用抽象类完成了 Rico Kahler 的回答,以避免使用联合类型

abstract class MapItem {
    originChar: string;

    constructor(){}
}

class Wall extends MapItem {
    brick: string;

    constructor(){
        super();
        this.brick = "jolies briques oranges";
    }

    // Wall methods ...
}

class Critter extends MapItem {
    CritterProperty1: string[];
    CritterProperty2: string;

    constructor() {
        super();
        this.CritterProperty1 = "n ne e se s so o no".split(" ");        
    }

    // Critter methods ...
}

interface Ilegend {
    [k: string]: new () => MapItem; 
}

let theLegend: Ilegend = {
    "X": Wall,
    "o": Critter
}

谢谢。

里科·卡勒

你的问题在于你的对象theLegend

打字稿需要一个Wall 或 Critter实例,但您为它提供了一个类型。

let theLegend: Ilegend = {
    "X": Wall, // `Wall` is a type not an instance, it is `typeof Wall` or the Wall type
    "o": Critter // `Criter` is a type not an instance
}

类似以下内容将起作用:

let theLegend: Ilegend = {
    X: new Wall(), // now it's an instance!
    o: new Critter()
}

编辑:

现在阅读您链接的 javascript 页面,似乎我错过了您的意图。如果你想创建一个接受构造函数的接口,那么我会输入Ilegend如下:

interface Legend {
    [k: string]: new () => (Critter | Wall)
}

// now you can define an object with this type

let legend: Legend = {
    // here `Critter` actually refers to the class constructor
    // that conforms to the type `new () => (Critter | Wall)` instead of just a type
    something: Critter,
    somethingElse: Wall
}

const critter = new legend.something() // creates a `Critter`
const wall = new legend.somethingElse() // creates a `Wall`

// however, the type of `critter` and `wall` are both `Critter | Wall`. You'd have to use type assertion (i.e. casting) because typescript can't tell if its either a Critter or a Wall

现在接口允许任何字符串作为键,它期望每个值都是一个函数,您可以调用new它来获取 aCritter或 aWall

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章