【发布时间】:2020-03-26 12:55:39
【问题描述】:
我正在编写一个转换器,它使用查找对象将元组数组转换为对象,该对象告诉函数哪些字符串映射到哪些属性。但是,我找不到一种方法来告诉 typescript 它是一个具有特定类型的元组数组,生成的元组总是联合。下面是它的样子:
interface EndObj {
a: number;
b: string;
c?: number;
}
interface InitObj {
d: string;
e: string;
f: string;
}
const map = {
d: 'a',
e: 'b',
f: 'c'
} as const;
type MapType = typeof map;
type ResultTuple<T extends keyof InitObj> = [T, EndObj[MapType[T]]];
type ResultTupleArray = ResultTuple<keyof InitObj>[];
const resultObj: ResultTupleArray = [['d', 1], ['e', 3], ['f', 3]]; // invalid! the value of 'e' should only allow strings
我认为打字稿允许这样做的原因是,因为ResultTupleArray 是用keyof InitObj 定义的,所以生成的元组数组泛型总是相同的,所以T 总是相同的,而不是特定于每个数组条目,因此只能用联合来描述。
我是这样发现的:
const undetected: ResultTuple<keyof InitObj> = ['e', 4]; // should be invalid
const detected: ResultTuple<'e'> = ['e', 4]; // actually shows an error for 4 (Type 'number' is not assignable to type 'string'.)
对于一些上下文,转换器的外观如下:
function mapInitToEnd(resultO: ResultTupleArray) {
const endObj: EndObj = {
a: -1,
b: ''
};
for (const tuple of resultO) {
const [key, val] = tuple;
const mappedKey = map[key];
endObj[mappedKey] = val;
}
return endObj;
}
有没有办法告诉 typescript 泛型只对元组数组中的每个条目有效,而不是对整个数组有效?
【问题讨论】:
标签: typescript tuples