实现说明
typeof 类型运算符从值派生类型的核心是函数 describe。
使用要点
- 演示输出是带标签的(
literal type holds:),每个操作都会留下自己的一行标注。
常见问题
不安装任何包也能运行吗?
可以,开箱即跑——没有引用任何内建 API 之外的东西。 文件在加载时定义 describe。
入口签名:function describe(config: AppConfig)
核心语句
return config.host + ':' + config.port + ' retries<=' + config.retries.max;
代码示例
const DEFAULT_CONFIG = {
port: 8080,
host: 'localhost',
retries: { max: 3, backoffMs: 250 },
} as const;
// The typeof type operator lifts the value's shape into the type system
type AppConfig = typeof DEFAULT_CONFIG;
function describe(config: AppConfig): string {
return config.host + ':' + config.port + ' retries<=' + config.retries.max;
}
console.log(describe(DEFAULT_CONFIG));
// AppConfig carries literal types from the value: port is 8080, not number
const portCheck: 8080 = DEFAULT_CONFIG.port;
console.log('literal type holds:', portCheck === 8080);