type-challenges/README.zh-CN.md at main · type-challenges/type-challenges · GitHub
https://github.com/TIMPICKLE/type-challenges/blob/main/questions/00010-medium-tuple-to-union/README.zh-CN.md
lets do it , mate!
首先概念澄清:
JS: const let
TS:type interface
typeof作用是:将js世界的东西转化为ts类型世界的内容,参与计算
const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const;
type r = typeof tuple;
r 显示的是:type r = readonly ["tesla", "model 3", "model X", "model Y"]
const作用:定义为字面量类型
意味着不能被更改,只能是这个值。
首先用JS来实现一遍:
1. 接受一个数组
2. 返回一个object
3. 循环对数组赋值
function tupleToObject(array){
// 确定返回值是一个对象
const obj = {};
array.array.forEach(element => {
obj[elemnet] = element;
});
return obj;
}
现在用TS来实现一遍:
返回一个对象
//type TupleToObject <T extends readonly any[]> = any;
//我们需要返回一个对象 所以要改为
type TupleToObject <T extends readonly any[]> = {};
type TupleToObject <T extends readonly any[]> = {
// 遍历数组 T[number] (TS的语法)
[P in keyof T[number]]:P
};
过啦!
union的题的明天再写~