Created
March 15, 2022 18:58
-
-
Save tianhuil/f5539405f0e0c04a500356f21a11a621 to your computer and use it in GitHub Desktop.
Type Assertions in typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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