实现说明
keyList 定义在模块顶层,中间不经过函数作用域。
使用要点
- 直接运行文件,输出会带上标签,比如
slot 2:、slot 0:、id 7:——输出的每一行都能指回产生它的那次调用。
常见问题
这段代码会引入外部包吗?
不涉及外部包,每个调用都落在内建 API 上。 跨调用保留的状态放在这些顶层绑定里:keyList。
核心语句
const names: Record<number, string> = { 7: 'delta' };
const keyList = Object.keys(names);
const slots: Slots = [];
代码示例
// Numeric index signatures type access by number position
type Slots = { [index: number]: string | undefined };
const slots: Slots = [];
slots[2] = 'charlie';
console.log('slot 2:', slots[2]);
console.log('slot 0:', slots[0] ?? 'empty');
// Numeric keys stringify at runtime — Object.keys always returns strings
const names: Record<number, string> = { 7: 'delta' };
console.log('id 7:', names[7]);
const keyList = Object.keys(names);
console.log('runtime keys:', keyList.join(','), '| first key type:', typeof keyList[0]);