Odinodin
Odinodin

Reputation: 2177

Typescript type error when filtering undefined from array

I want to filter undefined items from an array like so

type Kind = 'foo' | 'bar'

const someFunc = () : Array<{ kind: Kind, name: string }> => {
    return [{ kind: 'foo', name: 'a' }].filter(x => x !== undefined)
}

Gives the following type error:

Type '{ kind: string; name: string; }[]' is not assignable to type '{ 
kind: Kind; name: string; }[]'.
Type '{ kind: string; name: string; }' is not assignable to type '{ 
kind: Kind; name: string; }'.
Types of property 'kind' are incompatible.
  Type 'string' is not assignable to type 'Kind'.

Why does it fail, and how to handle it?

Upvotes: 0

Views: 244

Answers (2)

Ian Vasco
Ian Vasco

Reputation: 1340

You can create a new variable to declare the type of kind. This is because TypeScript is inferring that kind is a string.

type Kind = "foo" | "bar"

const someFunc = (): Array<{kind: Kind, name: string}> => {
    const kind: Kind = 'foo'
    return [{ kind, name: 'a' }].filter(x => x !== undefined)
}

Upvotes: 1

Grabofus
Grabofus

Reputation: 2034

Because TypeScript is inferring the type of your array from [{ kind: 'foo', name: 'a' }]. If you tell it what the type of the array is, it'll be happier. :)

type Kind = 'foo' | 'bar'

const someFunc = (): Array<{ kind: Kind; name: string }> => {
    const array: Array<{kind: Kind; name: string}> = [{ kind: 'foo', name: 'a' }];
    return array.filter(x => x !== undefined)
}

Upvotes: 1

Related Questions