type constraints 类型约束

https://dev.to/_gdelgado/type-constraints-in-typescript-34ek

A type constraint is a "rule" that narrows down the possibilities of what a generic type could be.

 

We can thus narrow the possibilities of the generic type T to allow allow JSON values as follow:

const send = <T extends JSONValues>(data: T): Promise<null> => {
  // ...
}
 

The only difference is that now we've appended extends JSONValues to the type variable declaration for T.

In plain english T extends JSONValues translates to, "T is a generic type that must conform to the definition of JSONValues".

posted @ 2023-04-26 10:37  hh9515  阅读(31)  评论(0)    收藏  举报