Home > Back-end >  multiple type with typescript
multiple type with typescript

Time:10-28

I have that object that I want to use as a type:

interface MyInput {
    id: string,
    label: string,
    setter: Function,
    type: string,
    value: string | string[] | boolean,
    options?: string[]
}

I have some errors like: Property 'map' does not exist on type 'string | boolean | string[]'. Type 'string | boolean | string[]' is not assignable to type 'boolean | undefined'.

The thing is that I will always know whether my value is string[], boolean or string with my type property.

Is there any solution to remove those errors without make 3 different interfaces?

Beside putting my value property to any or to create 3 diffent types, I do not known.

CodePudding user response:

You may define the interface with generic type, as in below code

interface MyInput<T = string | string[] | boolean> {
    id?: string,
    label?: string,
    setter?: Function,
    type?: string,
    value: T,
    options?: string[]
}

The actual type can be determined while defining variable, as in below code

let ip: MyInput<string[]> = {
    value: []
}

ip.value.map((v) => {...})

CodePudding user response:

You will need to do something to cast it or annotate it with a @ts-ignore. e.g.

(input.value as string[]).map(...
  • Related