簡體   English   中英

打字稿中相同實現的不同返回類型推斷

[英]Different return type inference for same implementation in typescript

我想了解為什么以下 2 個實現之間存在類型差異。 它們都生成相同的結果,但它們的返回類型各不相同。

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<"string" | "number", Function> , 至於第二個代碼

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<"first" | “第二” | “第三”,功能>

不同之處在於to在兩個版本的typeof to引用不同的變量:在第一個片段中它引用類型為{ [as: string]: any }局部變量,在另一個片段中它引用全局變量to . 該變量是通過分配給它的值鍵入的,該值的類型為{ first: string, second: string, third: string }

函數的實際類型應該是(這實際上符合它的行為,它允許打字稿根據to參數推斷通用參數):

  <T> (to: Record<T, any>): Record<T, Function>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM