题目
传入一个元组类型,将这个元组类型转换为对象类型,这个对象类型的键/值都是从元组中遍历出来。
const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
type result = TupleToObject<typeof tuple> // expected { tesla: 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y'}
单元测试
import { Equal, Expect } from '@type-challenges/utils'
const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
type cases = [
Expect<Equal<TupleToObject<typeof tuple>, { tesla: 'tesla'; 'model 3': 'model 3'; 'model X': 'model X'; 'model Y': 'model Y'}>>,
]
// @ts-expect-error
type error = TupleToObject<[[1, 2], {}]>
typeof 作用
const let JS 世界
type interface 类型世界
通过 typeof 由 JS 世界穿越到类型世界
as const 作用
const tuple = ['tesla', 'model 3', 'model X', 'model Y'];
type r = typeof tuple; // r 为 string[] 类型
字面量类型
let str = "123";
type s = typeof str; // s 为 string 类型
str = "123123123123";
const strConst = "234"; // 常量
type sc = typeof strConst; // sc 为 "234" 类型
sc = "123123123"; // 不能被修改
通过 as const 语法,可以把 tuple 写死readonly ["tesla", "model 3", "model X", "model Y"]
@ts-expect-error
期望下面会报错,相当于
expect(() => {
type error = TupleToObject<[[1, 2], {}]>;
}).toThrow();
通过 JS 解题
functon tupleToObject (array) {
// 如果 array 的类型不为 string / number / symbol 则抛出 error
const obj = {};
array.forEach(val => {
obj[val] = val;
});
return obj;
}
知识点
- 返回一个对象
- 遍历 array
对象的 key 只能是 number string symbol
翻译为 TS
type TupleToObject<T extends readonly (string | number | symbol)[]> = { [P in T[number]] : P; };
通过 keyof array 可以获取索引
返回一个对象
- 遍历 array
- T[number]