我想了解以下两个实现之间为什么会有类型差异。两者都产生相同的结果,但是两者的返回类型都不同。
const from = [
() => console.log('first'),
() => console.log('second'),
() => console.log('third')];
const to = {
first: 1,
second: 2,
third: 3,
};
const aggFn = (from: Function[], to: { [as: string]: any }): Record<keyof typeof to, Function> => {
return ({
first: from[0],
second: from[1],
third: from[2],
} as unknown) as Record<keyof typeof to, Function>;
};
const agg = aggFn(from, to);
这里agg的返回类型是Record ,其中第二个代码
const from = [
() => console.log('first'),
() => console.log('second'),
() => console.log('third')];
const to = {
first: 1,
second: 2,
third: 3,
};
const aggFn2 = <T>(from: Function[], to: { [as: string]: any }): T => {
return ({
first: from[0],
second: from[1],
third: from[2],
} as unknown) as T;
};
const agg2 = aggFn2<Record<keyof typeof to, Function>>(from, to);
返回类型为Record
不同之处在于,to
的两个版本中的typeof to
引用不同的变量:在第一个代码段中,它引用的是{ [as: string]: any }
类型的local variable