Reputation: 15336
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)
}
Upvotes: 1
Views: 87
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