← 中文资源

简体中文版本

typeof 类型运算符从值派生类型

typeof 类型运算符把运行时常量的完整形状提升为类型:嵌套字段与字面量类型自动保留,函数参数与配置同源,无需手写接口。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

localhost:8080 retries<=3
literal type holds: true

实现说明

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);