1

I'm trying to understand the use case where typescript allows instances to pass union type type-checking when it doesn't pass any individual component. The example I'm looking at is using types

type Bar = {
  bar: true
  bar2: number
}
type Baz = {
  baz: number
}
type Foo = Bar | Baz

which catches

const bazArg: Baz = {baz: 5, bar: true}

as a type error, but does not catch

const bazArg: Foo = {baz: 5, bar: true}

This allows bugs like

const fn = (foo: Foo): number => 'bar' in foo ? foo.bar2 : foo.baz
const bazArg: Foo = {baz: 5, bar: true}
console.log(fn(bazArg)) // logs undefined

typescriptland link

Steven Noble
  • 10,204
  • 13
  • 45
  • 57
  • See the answer to the linked question. TypeScript does not perform excess property checking on cross-member union fields (for non-discriminated unions). – jcalz Nov 30 '22 at 16:01
  • It's annoying because this is incorrect for strict typescript "Types in TypeScript are open in the sense that an object has to have at least the properties described by a type for it to match. So the object { value: 7, data: 'test', note: 'hello' } matches the type { value: number, data: string }, even though it has that excess note property. So your c variable is indeed a valid sth." just try: type T = { value: number, data: string } const x: T = { value: 7, data: 'test', note: 'hello' } – Steven Noble Nov 30 '22 at 18:14
  • see https://www.typescriptlang.org/play?#code/C4TwDgpgBAKlC8UDeUBuBDANgVwgLigDtsBbAIwgCcAaKAE3WHQIGdhKBLQgcygF8AUAGMA9oTZQAHgTiIUGHPigB2WgyYEA5MAhtNtQiJ1aAFhEyYRm-gKA – Steven Noble Nov 30 '22 at 18:17
  • The statement is correct, but I'm happy to edit if it's confusing or misleading. See [this playground link](https://tsplay.dev/mM8xZN), you can indeed assign that object to that type. But when you do so directly via an *object literal*, it prevents the assignment due to excess property checking... which is essentially a linter feature and not really a type safety issue. – jcalz Nov 30 '22 at 18:19
  • 1
    Ah I see the distinction. Thank you for the clarification. – Steven Noble Nov 30 '22 at 18:23
  • 1
    I've edited the other answer to be a little more explicit, hope that helps – jcalz Nov 30 '22 at 18:23

0 Answers0