Created
April 4, 2022 06:04
-
-
Save qnighy/5b13e2a0390d6fcbfe0b766d90fb48d6 to your computer and use it in GitHub Desktop.
TypeScript type testing util less than in 40 lines
This file contains 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
// Copyright 2022 Masaki Hara | |
// Licensed in MIT https://opensource.org/licenses/MIT | |
type Predicate<T> = { | |
co?: (() => T) | undefined; | |
contra?: ((x: T) => void) | undefined; | |
}; | |
function expectType<T>() { | |
return { | |
to(_pred: Predicate<T>): void {} | |
}; | |
} | |
type AssignableToPredicate<T> = { | |
co?: undefined; | |
contra(x: T): void; | |
}; | |
function beAssignableTo<T>(): AssignableToPredicate<T> { | |
return { contra(_x: T) {} } | |
} | |
type AssignableFromPredicate<T> = { | |
co(): T; | |
contra?: undefined; | |
}; | |
function beAssignableFrom<T>(): AssignableFromPredicate<T> { | |
return { co() { return null as any; } }; | |
} | |
type TypeEqualPredicate<T> = { | |
co(): T; | |
contra(x: T): void; | |
}; | |
function beTypeEqual<T>(): TypeEqualPredicate<T> { | |
return { co() { return null as any; }, contra(_x: T) {} } | |
} | |
// Type predicate self check | |
expectType<number>().to(beAssignableTo<number>()); | |
// @ts-expect-error | |
expectType<number>().to(beAssignableTo<string>()); | |
expectType<number>().to(beAssignableTo<number | string>()); | |
// @ts-expect-error | |
expectType<number>().to(beAssignableTo<never>()); | |
expectType<number>().to(beAssignableFrom<number>()); | |
// @ts-expect-error | |
expectType<number>().to(beAssignableFrom<string>()); | |
// @ts-expect-error | |
expectType<number>().to(beAssignableFrom<number | string>()); | |
expectType<number>().to(beAssignableFrom<never>()); | |
expectType<number>().to(beTypeEqual<number>()); | |
// @ts-expect-error | |
expectType<number>().to(beTypeEqual<string>()); | |
// @ts-expect-error | |
expectType<number>().to(beTypeEqual<number | string>()); | |
// @ts-expect-error | |
expectType<number>().to(beTypeEqual<never>()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment