type constraints 类型约束

阅读 63

2023-04-29

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".



精彩评论(0)

0 0 举报