禁用noUncheckedIndexedAccess时,实现其等效行为的safeIndex函数
实现满足类型约束的safeIndex函数(禁用noUncheckedIndexedAccess时)
核心思路
通过TypeScript的条件类型与索引类型区分两种场景:对象是带明确键名的字面量类型,还是带有字符串/数字索引签名的类型,以此模拟noUncheckedIndexedAccess的类型检查行为。
代码实现
type SafeIndexResult<T, K extends PropertyKey> = T extends Record<K, infer V> ? V : T extends Record<string, infer V> | Record<number, infer V> ? V | undefined : never; function safeIndex<T, K extends PropertyKey>(obj: T, key: K): SafeIndexResult<T, K> { return obj[key as keyof T] as SafeIndexResult<T, K>; }
场景验证
- 访问字面量对象的存在键
const obj1 = { x: 1 }; const val1 = safeIndex(obj1, 'x'); // 类型为number
字面量对象的键明确存在,返回值类型直接对应键的类型。
- 访问字面量对象的不存在键
const obj2 = { x: 1 }; const val2 = safeIndex(obj2, 'y'); // 类型错误:类型'"y"'的参数不能赋给类型'"x"'的参数
TypeScript会检查传入的键是否属于对象的已知键集合,不存在则直接触发类型错误。
- 访问带字符串索引签名的对象
const obj3: { [key: string]: number } = { x: 1, y: 2 }; const val3 = safeIndex(obj3, 'x'); // 类型为number | undefined
带索引签名的对象无法保证指定键一定存在,因此返回值类型自动加上undefined,与noUncheckedIndexedAccess的行为一致。
原理说明
SafeIndexResult条件类型先判断对象是否包含传入的明确键,是则返回对应值类型;- 若对象带有字符串/数字索引签名,返回值类型自动追加
undefined; - 函数内部通过类型断言确保返回值符合推导的类型,同时利用TypeScript的类型检查机制限制键的合法性。
内容的提问来源于stack exchange,提问作者joshuahhh
相关产品推荐
相关产品推荐

