Skip to content

Instantly share code, notes, and snippets.

@tianhuil
Created March 15, 2022 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tianhuil/f5539405f0e0c04a500356f21a11a621 to your computer and use it in GitHub Desktop.
Save tianhuil/f5539405f0e0c04a500356f21a11a621 to your computer and use it in GitHub Desktop.
Type Assertions in typescript
// Type assertions, before I discovered https://www.npmjs.com/package/type-assertions
type AssertExtends<A, B> = A extends B ? true : false
export const assertExtends = <A, B>(_: AssertExtends<A, B>): void => {}
export const assertInstance = <B>(
a: any,
_: AssertExtends<typeof a, B>
): void => {}
assertExtends<'abc', string>(true)
assertExtends<string, 'abc'>(false)
interface Foo {
foo: number
bar: string
}
assertExtends<{ foo: number; bar: string }, Foo>(true)
assertExtends<{ foo: number; bar: string; baz: string }, Foo>(true)
assertExtends<{ foo: number; bar: number }, Foo>(false)
assertExtends<{ foo: number }, Foo>(false)
assertInstance<Foo>({ foo: 1, bar: 's' }, true)
assertInstance<Foo>({ foo: 1, bar: 's' }, true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment