Alex Craft
Alex Craft

Reputation: 15336

Why TypeScript incorrectly infers the return type?

UPDATE: TypeScript message was correct, the return type of that function could be an empty string.

The snippet below won't compile in TypeScript with strictNullCheck option.

The code is correct, but TS wrongly infers that this (id) => id && /^[a-z0-9\-]+$/.test(id) expression can return among other values empty string '' and complains.

type Validators<D> = { 
  [K in keyof D]: (value: D[K] | undefined) => true | false | undefined
}

interface Post {
    id?: string
}

const validators: Validators<Post> = {
    // Complains about this line
    id: (id) => id && /^[a-z0-9\-]+$/.test(id) 
}

Playground

Upvotes: 1

Views: 87

Answers (1)

Rachael Dawn
Rachael Dawn

Reputation: 899

A little trick I learned a while ago to assert non-null values is to do a double !!.

type Validators<D> = { 
  [K in keyof D]: (value: D[K] | undefined) => true | false | undefined
}

interface Post {
    id?: string
}

const validators: Validators<Post> = {
    id: (id) => !!id && /^[a-z0-9\-]+$/.test(id)
}

This code doesn't complain, but the thing it is unsure of is the id variable. By doing !!id, you're asserting it's falsiness, then flipping it to in essence assert its "truthiness".

Upvotes: 2

Related Questions