简体   繁体   中英

Declare type of a object key

I have a XInterface like so:

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

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.

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. With that in mind, you will always have to check the content of foo. A better approach is to simply convert foo to a function.

You can define XInterface like:

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

and let suppose that you have a function

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

so when you define your object

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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