示例工程 06-generics
06-generics/04-const-type-parameter/src/main.ts
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// 演示:const 类型参数把推断压到字面量,不需要 as const
export function tuple<const T extends readonly unknown[]>(items: T): T {
return items;
}
export function route<const T extends string>(path: T): { path: T } {
return { path };
}
export function run(log: (msg: string) => void = console.log): string[] {
const pair = tuple(['a', 'b']);
const home = route('/home');
const lines = [
pair.join(','),
home.path,
tuple([1, 2, 3]).length.toString(),
];
for (const line of lines) {
log(line);
}
return lines;
}