简体   繁体   English

声明 object 密钥的类型

[英]Declare type of a object key

I have a XInterface like so:我有一个像这样的XInterface

export interface XInterface {
    foo: (() => Foo[]) | Foo[],
    bar: string,
    baz: number
}

Then, using the interface to declare an object I would like to the type of foo to be Foo[] , like然后,使用接口声明一个 object 我想foo的类型是Foo[] ,比如

const myObj: XInterface = {
    [myFoo1, myFoo2],
    'bar',
    1
}

but as I am already using the : to declare my array of Foo, I don't know how to ensure that foo is an array, not a function that returns an array.但是由于我已经在使用:来声明我的 Foo 数组,所以我不知道如何确保 foo 是一个数组,而不是返回数组的 function。

How can I achieve that?我怎样才能做到这一点?

This is a pattern I would follow.这是我会遵循的模式。 In the future you will pass this object to somewhere XInterface is expected, which does not know if foo is a function or an array.将来,您将把这个 object 传递到 XInterface 预期的地方,它不知道 foo 是 function 还是数组。 With that in mind, you will always have to check the content of foo.考虑到这一点,您将始终必须检查 foo 的内容。 A better approach is to simply convert foo to a function.更好的方法是简单地将 foo 转换为 function。

You can define XInterface like:您可以像这样定义 XInterface:

foo: Foo[],
bar: string,
baz: int

and let suppose that you have a function假设你有一个 function

someFuntion(): Foo[] { .....};

so when you define your object所以当你定义你的 object

const myObj: XInterface = {
   foo: someFuntion(),
   bar: 'bar',
   baz: 1
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM