Gurwinder Singh
Gurwinder Singh

Reputation: 39477

Type checking on return type

I have following piece of code:

interface Box<T> {
  value: T | null;
}

function foo<T>(b: Box<T>, defaultVal: T): T {
  return b.value || defaultVal;
}

const s: string | null = null;
const t = foo({ value: s }, { value: "def" });
console.log(t);

Why does this compile? I expected to get type error on second argument.

Upvotes: 1

Views: 231

Answers (1)

Oblosys
Oblosys

Reputation: 15106

It's because even though s has a string | null type signature, it's type is narrowed to null because of the assignment. You can see this if you hover over s. If you hover over foo, it shows T is chosen as {value: string}, which makes the application type correct.

For an s that has an actual union type, you'll get the expected error:

const test = (s: string | null) => {
  const t = foo({ value: s }, { value: "def" }); // Error, as expected
}

TypeScript playground

Upvotes: 2

Related Questions