示例工程 15-type-testing-api-design
15-type-testing-api-design/01-type-assertions/types.test-d.ts
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
type Equal<A, B> =
(<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
import { add } from './src/main.js';
// 正例:返回值类型必须精确
type Case1 = Expect<Equal<ReturnType<typeof add>, number>>;
// 正例:参数元组
type Case2 = Expect<Equal<Parameters<typeof add>, [a: number, b: number]>>;
// 负例:必须带原因,否则编译器会报未命中
// @ts-expect-error: 字符串不能传给 add
const bad = add('1', 2);
export { bad };