示例工程 06-generics
06-generics/04-const-type-parameter/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 { route, tuple } from './src/main.js';
// const 类型参数保留字面量与只读元组
type Case1 = Expect<Equal<ReturnType<typeof tuple<readonly ['a', 'b']>>, readonly ['a', 'b']>>;
type Case2 = Expect<Equal<ReturnType<typeof route<'/home'>>, { path: '/home' }>>;
const pair = tuple(['x', 'y']);
const home = route('/home');
type Case3 = Expect<Equal<typeof pair, readonly ['x', 'y']>>;
type Case4 = Expect<Equal<typeof home, { path: '/home' }>>;
// 普通泛型(没有 const)会拓宽
function widened<T extends readonly unknown[]>(items: T): T {
return items;
}
const plain = widened(['x', 'y']);
type Case5 = Expect<Equal<typeof plain, string[]>>;
export { pair, home, plain };