打字稿中相同实现的不同返回类型推断

问题描述 投票:0回答:1

我想了解以下两个实现之间为什么会有类型差异。两者都产生相同的结果,但是两者的返回类型都不同。

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

javascript typescript type-inference
1个回答
0
投票

不同之处在于,to的两个版本中的typeof to引用不同的变量:在第一个代码段中,它引用的是{ [as: string]: any }类型的local variable

,在另一个代码中,它引用的是全局变量
© www.soinside.com 2019 - 2024. All rights reserved.