7 Matching Annotations
  1. Oct 2020
  2. Oct 2019
    1. type FindByTag<Union, Tag> = Union extends { tag: Tag } ? Union : never; function cast<A extends Foo["tag"]>(foo: Foo, expectedTag: A): FindByTag<Foo, A> { if (foo.tag !== expectedTag) throw Error(`expected tag ${expectedTag} but was ${foo.tag}`) return foo as FindByTag<Foo, A>; }
    1. type Type = 'a' | 'b'; type AShape = { a: 'a' }; type BShape = { b: 'b' }; type Props<T extends Type> = { type: T, shape: T extends 'a' ? AShape : BShape, }; class Test<T extends ID> extends React.Component<Props<T>> { render() { const { type, shape } = this.props; switch (type) { case 'a': return <>{shape.a}</>; // Ideally would narrow `shape` here, instead of `AShape | BShape` default: return <>{shape.b}</>; } } } <T type="a" shape={{ a: 'a' }} /> // No error in ideal case <T type="a" shape={{ b: 'b' }} /> // error in ideal case
    2. type NumberType = (() => number) | number; function double<T extends NumberType>( num: T ) : T { if (typeof num === "number") return num * 2; return () => num() * 2; }