#Why does TS allow assigning undefined to a required type?

21 messages · Page 1 of 1 (latest)

heavy roostBOT
#

@hollow dove Here's a shortened URL of your playground link! You can remove the full link from your message.

the_og_mp#0

Preview:```ts
interface MyType {
x: number | null
}

const fakeNews = {
x: undefined,
} as MyType```

honest meadow
#

what do you mean? there is a type error there. also as isn't really checking the type in a normal way—it's a type assertion

hollow dove
#

interface MyType {
x: number | null
}

const fakeNews = {
x: null
} as MyType

if (fakeNews.x !== undefined) {
console.log("My number is " + fakeNews.x)
}

heavy roostBOT
#
interface MyType {
  x: number | null
}

const fakeNews: MyType = {
  x: undefined
//^
// Type 'undefined' is not assignable to type 'number | null'.
}
#
the_og_mp#0

Preview:```ts
interface MyType {
x: number | null
}

const fakeNews = {
x: null,
} as MyType

if (fakeNews.x !== undefined) {
console.log("My number is " + fakeNews.x)
}```

hollow dove
#

Why does it allow me to compare undefined to X

#

When X can never be undefined

honest meadow
#

the rules for allowed comparisons are pretty loose, probably to make it easy to deal with untyped/badly typed JS codebases

hollow dove
#

Is there a way to disable that feature?

#

Or to force the compiler to be more strict about that

honest meadow
#

but allowing you to check for a value that will never exist isn't really unsafe (not any more than allowing you to write if (false) {} is unsafe)

hollow dove
#

Gotcha. I guess the idea I was hoping for was that in our company codebase I don't want to allow senseless checks like that, because it might trick people into thinking they actually accomplished something and wrote correct code when they write if (foo.x !== undefined) { ... } against an object that has a property of x: number | null.

#

They would incorrectly think they are working with a number when in reality it could be null

#

Thanks for your help and explanation though

#

I wasn't aware typescript didn't handle this

honest meadow
#

well the type checker will catch that:

heavy roostBOT
#
const foo = {
  x: Math.random() > 0.5 ? 42 : null
}

if (foo.x !== undefined) {
  const y = foo.x + 1
//          ^^^^^
// 'foo.x' is possibly 'null'.
}
hollow dove
#

Ah, cool, so it doesn't disallow the bad if statement but it will actually complain when they actually try to use it, OK that's fine then

dreamy belfry
#

Yeah - IIRC the allowing unnecessary nullish checks is because it's often useful for JS consumers.

#
function myApi(foo: string) {
   if(foo == null) throw new Error("foo is a required param");
}