定义接口:具有未知数量和属性名称的对象

Flo*_*dis 3 interface typescript

我有一个对象 foo

interface Foo {
    fooId: string;
    otherStuff: any;
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个对象 fooCollection,它是一个包含未定义数量的 foos 的对象。每个属性都是一个等于 fooId 的字符串。如何为 fooCollection 定义准确的接口?

到目前为止,我想出了这个:

interface FooCollection {
    [key: string]: Foo;
}
Run Code Online (Sandbox Code Playgroud)

- 我怎么能告诉 ts 财产的数量可以是任何东西?

- 我可以更准确地说明道具名称,说它是 fooId 而不是任何字符串吗?

Mat*_*hen 5

索引签名[key: string]: Foo已经允许任意数量的属性(零个或多个)。

编写一个类型,每个属性的名称比赛强制实施fooId的的Foo目标是超越打字稿的类型系统的能力。您可以编写一个FooCollection在所使用的 ID 集中通用的类型,这将允许您编写一个通用函数来验证手写FooCollection文字:

interface Foo<Id extends string> {
    fooId: Id;
    otherStuff: any;
}

type FooCollection<Ids extends string> = { [Id in Ids]: Foo<Id> };

function checkFooCollection<Ids extends string>
    (fooCollection: FooCollection<Ids>) { 
    return fooCollection;
}

// OK
let c1 = checkFooCollection({
    a: {fooId: "a", otherStuff: 5}
});

// Error
let c2 = checkFooCollection({
    a: {fooId: "b", otherStuff: 5}
});
Run Code Online (Sandbox Code Playgroud)

但是,如果您FooCollection在运行时构建对象,则这种方法不太可能比原始方法提供更有意义的检查。