簡體   English   中英

如何在 function 正文中訪問通用 TypeScript 類型?

[英]How to access generic TypeScript type in function body?

在 TypeScript function 上使用泛型類型:

const func: <T extends number>() => void = () => {
   const x: T = 1
}

發出以下錯誤:

Cannot find name 'T'.  TS2304

    69 | const func: <T extends number>() => void = () => {
  > 70 |    const x: T = 1
       |             ^
    71 | }

如何在 function 中使用泛型類型(而不僅僅是在其簽名上)?

如果要鍵入箭頭函數,請嘗試使用此答案中的隱含鍵入方法。

const func = <T extends number>(x: T) => x;

使用替代 function 表示法使該錯誤消失:

function func<T extends number>(): void {
   const x: T = 1
}

相反,我們得到以下錯誤,這是有道理的:

Type '1' is not assignable to type 'T'.
  '1' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'number'.  TS2322

    69 | export function func<T extends number>(): void {
  > 70 |    const x: T = 1
       |          ^
    71 | }

暫無
暫無

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

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