0

I have custom types which is the following:

hero?: string
power?: string

I want to add those type into an array, which is part of another type

type Superheroes = {
character: string[] | []
villains: number | null
city: string

}

When I try to use the type (see below) I get the following error Typescript: Type 'string | undefined' is not assignable to type 'string'

return {
character: [hero, power],
villains: 2 || null,
city: 'new york' || null
}

What is the correct way to define hero and power types inside the character array?

1
  • Could you make an edit in the example please tsplay.dev/mL9MKW ? Commented Jun 1, 2021 at 15:12

2 Answers 2

1

To make it assignable you should define your Superheroes type like that:

type Superheroes = {
  character: (string | undefined)[]
  villains: number | null
  city: string
}

or if there are always no more than two elements in character array:

type Superheroes = {
  character: [string?, string?]
  villains: number | null
  city: string
}

TS playground

Sign up to request clarification or add additional context in comments.

Comments

0

You can change the type to :

city: string || null

or change the assign of the city attribute to :

city: 'new york'

without the array or null.

2 Comments

The issue is with the hero and power types inside the character array. The city being an array was a typo which is now fixed
oh ok. I see that you add question mark to hero?: string and power?: string without initialization and that could be undefined, I think you can try initialization hero and power like this: hero?: string = ''; power?: string = ''; to avoid the error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.