Edgaras Karka
Edgaras Karka

Reputation: 7852

Why TypeScript doesn't detect error when use undefined for boolean?

I have the interface:

interface Example {
  foo: boolean
}

later I use something like:

getFoo = (): Example => {foo: undefined}

without ts error. It is normal? If it is valid, is it good a practice to use undefined in situations like that?

Upvotes: 1

Views: 120

Answers (1)

Pac0
Pac0

Reputation: 23149

It will consider it as an error if you use the TypeScript (2.0+) compiler option

--strict-null-checks

in this case, undefined and/or null will be allowed only if you explicity state it with a union type :

interface Example {
  foo: boolean | null | undefined
}

Probably for backward compatibility issues, the default behavior was decided not to use strict checks.

more info here : https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html


for the use of undefined, I can't say if it's good or bad practice (I think more context is needed). However, you can use the optional interface fields with ? :

interface Example {
  foo?: boolean
} 

Upvotes: 3

Related Questions