#why does this work?

6 messages · Page 1 of 1 (latest)

hushed geode
#

While experimenting with generic type unions, I discovered a behavior of typescript that causes runtime errors despite the compiler's clear ability to detect wrong types and report them at build time.

here is the code snippet which will always fail

type MyVar<A, B> = {
  a: A;
  b: B;
};

const make = (): MyVar<number, string> => { 
  let a = 0;
  let b = "str";
  return Math.random() > 0.5 ? { a } as MyVar<number, never>: { b } as MyVar<never, string>;
}

let inst = make();
console.log(inst.a.toFixed());
console.log(inst.b.concat("1"));
ebon spearBOT
#

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

.kpap#0

Preview:```ts
type MyVar<A, B> = {
a: A
b: B
}

const make = (): MyVar<number, string> => {
let a = 0
let b = "str"
return Math.random() > 0.5
? ({a} as MyVar<number, never>)
: ({b} as MyVar<never, string>)
}

let inst = make()
console.log(inst.a.toFixed())
...```

timber lichen
#

well you're asserting that { a } and { b } are things that they are not

#

ts can't detect wrong types when you confidently incorrectly assert that they aren't wrong

weary flicker
#

^ Type assertion is just unsafe.

#

Type assertion is just telling TS "shut up I'm an engineer and listen to me"