簡體   English   中英

定義類型時的通用約束

[英]Generic constraint when defining a type

我試圖為具有單個回調參數(也是一個函數)的函數提供一種類型,以使該回調的參數類型僅限於對象

但是我收到類型錯誤。 這是代碼:

function aaa(a: { n: number }) { }

type Cb = <T extends object>(a: T) => void
function ccc(fn: Cb) { }
// type error - why?
ccc(aaa)

類型錯誤:

Argument of type '(a: { n: number; }) => void' is not assignable to parameter of type 'Fn'.
  Types of parameters 'a' and 'a' are incompatible.
    Type 'T' is not assignable to type '{ n: number; }'.
      Type 'object' is not assignable to type '{ n: number; }'.
        Property 'n' is missing in type '{}'.

一個類似的通用約束,但適用於函數定義,可以正常工作:

function aaa(a: { n: number }) { }

function bbb<T extends object>(fn: (a: T) => void) { }
// all good
bbb(aaa)

兩者有什么區別? 我怎樣才能使前一個工作呢?

謝謝!

編輯

游樂場鏈接

問題在於常規函數aaa與通用函數簽名Cb不兼容。

您可能想將Cb聲明為普通函數簽名,但是Cb具有泛型類型參數

function aaa(a: { n: number }) { }

type Cb<T extends object> = (a: T) => void
function ccc<T extends object>(fn: Cb<T>) { }
// ok
ccc(aaa)

暫無
暫無

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

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