Declare type of a object key

Eduardo Sousa

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?

Matheus Ramalho

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Typescript, declare a variable type must be key of an object

What is the way to declare a method that apply only specific type of key of object?

Declare object type in class

declare Object with the same key names

How to declare a boolean OR object type?

Declare type object in an oracle package

Joi object key type

Add type as a key of an object

Type guard on an object key

Specify the type for a key in an object

In Delphi is there a point to declare a parameter of type object as const?

How to declare object of type class with multiple bounds

how to declare type of function property returned on object

Declare/change the current type of an object in Typescript

How to declare a type from an object literal in typescript?

How to declare iterable object of another interface type?

In Typescript, Is it possible to declare "type" from an existing object?

Object or Boolean how to declare type in Typescript

Typescript: Declare type of a keyof a generic object param

How to declare an object of arrays of custom type in typescript

How to declare a type of (string, IDictionary<string, object>)

Map object to type of a key of that object

How do you declare the type a property of an object in-place, without needing to declare the type of the entire object?

Declare typescript type with a generic key plus a predefined one

Rename key of typescript object type

Key of object type in the hadoop mapper

TypeScript type for "Object with key called ..."

Object index key type in Typescript

Object of custom type as dictionary key