开发者

Typescript unknown extends T deferred type

I开发者_如何学Python saw this code in a library code, my confusion is around unknown extends CustomTypes[K], my understanding is this is a deferred type and unknown is always assignable to CustomTypes[K], so my question is how this type is actually used, particularly in which case it resolve to false. Some example can be helpful.

/**
 * Extendable Custom Types Interface
 */

type ExtendableTypes =
  | 'Editor'
  | 'Element'
  | 'Text'

export interface CustomTypes {
  [key: string]: unknown
}

export type ExtendedType<
  K extends ExtendableTypes,
  B
> = unknown extends CustomTypes[K] ? B : CustomTypes[K]


You are probably supposed to augment the interface CustomType through Declaration Merging. When multiple interfaces of the same name exist, they are merged together.

// declared somewhere in the library
export interface CustomTypes {
  [key: string]: unknown
}

// declared somewhere in your code
export interface CustomTypes {
    Editor: number
}

The type of the property Editor in CustomTypes is now number instead of unknown.

ExtendedType checks if a property's type was augmented and returns the new type.

type Result1 = ExtendedType<'Editor', string>
//   ^? Result1: number

Passing 'Editor' and string to ExtendedType will return number now.


Playground

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜