如何使用界面描述此对象?

时间:2015-03-28 02:19:33

标签: typescript

我有一个看起来像这样的对象:

var MyObject = {
    property1: {
        name: "name1",
        args: [1, 2, 3, 4],
    },

    property2: {
        name: "name2",
        args: [1, 1],
    },
    ...
}

MyObject包含许多属性,每个属性都是一个包含字符串和数组数组的对象。

是否可以创建描述MyObject类型的界面?

1 个答案:

答案 0 :(得分:2)

如果要将MyObject定义为包含任意数量属性的对象,则可以使用Dictionary array type definition (TypeScript documentation)

这是字典界面的Typescript playground example

/**
 * Define a dictionary interface.
 */
interface IMyObjectDictionary {
    [property: string]: IMyProperty;
}


interface IMyProperty {
    name: string;
    args: number[];
}


// Define `obj1` to be an `IMyObjectDictionary`.
// 
// All properties must be `IMyProperty` instances.
var obj1: IMyObjectDictionary = {
    property1: {name: '', args: []}

    // You define as many `IMyProperty` properties
    // as needed.

    // But all properties *must* match the `IMyProperty` interface.
    //,property2: number    // <-- This would give a compiler error because it's not an `IMyProperty`.
};

// Must access properties using array notation.
var b = obj1['property1'];

// TypeScript knows that `b` is an `IMyProperty`.
b.name; // Valid
b.args; // Valid

// b.temp;  // <-- Invalid - `temp` does not exist on `IMyProperty`.
// b = 1; // <-- This would give a compiler error. 'number' is not an `IMyProperty`.

如果您需要混合类型的属性,则需要使用常规接口定义。

e.g。

interface IMyObjectDictionary {
    property1: IMyProperty;
    property2: IMyProperty;
    // ...

    // Allows properties that aren't `IMyProperty`
    // but you have to define all properties.
    index: number;
}