如何使用接口来描述这个对象?

How to describe this object using an interface?

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

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

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

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

是否可以创建一个描述 MyObject 类型的接口?

如果要将 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`.

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

例如

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

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