在 Typescript 中使用泛型类型加宽类型 [英] Widen a type with a type generic in Typescript

查看:38
本文介绍了在 Typescript 中使用泛型类型加宽类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,我想扩大按字面转换的对象的类型(使用as const"),因此它的属性将被推断为字符串或数字,而不是字面意义.

In certain cases I'd like to widen the type of an object which is casted literally (using "as const"), so it's properties will be inferred as strings or numbers, and not literally.

假设我有以下类型

const obj = [
   {
      type:"student", 
      name:"Yossi"
   }, 
   {
      type: "Teacher", 
      name: "Lili"
   }
] as const

type Person = typeof obj [number]

我希望从字面上推断 obj 的类型,但要更广泛地推断 Person,因此它的类型和名称是字符串.是否有可以允许以下内容的泛型:

I'd like the type of obj to be inferred literally, but Person to be Wider, so it's type and name are strings. Is there a generic which can allow the following:

type Person = Widen<typeof obj [number]>

推荐答案

有趣的案例.我们可以尝试通过映射类型来创建这样的实用程序.考虑:

Interesting case. We can try to create such utility by mapped types. Consider:

// it transforms our specific types into primitive origins
type ToPrimitive<T> =
  T extends string ? string
  : T extends number ? number
  : T extends boolean ? boolean
  : T;
// mapped types which will preserve keys with more wide value types
type Widen<O> = {
  [K in keyof O]: ToPrimitive<O[K]>
}
// using
type Person = Widen<typeof obj[number]>
const a: Person = {
  name: 'name', // string
  type: 'type' // string
}

我们可以扩展 ToPrimitive 以考虑其他类型,例如对象、数组,添加额外条件.

We can extend ToPrimitive to also consider other types like object, array by adding additional conditions.

正如我所见,您的 obj 元素类型或原始类型是一种 - {name: string, type: string}.然后我们可以通过以下方式从第一个元素创建一个类型:

As I see your obj type of elements in terms or primitive types is one - {name: string, type: string}. Then we can just create a type from a first element by:

type Person = Widen<typeof obj[0]>;
// and this nicely evaluates to:
type Person = {
    readonly type: string;
    readonly name: string;
}

这篇关于在 Typescript 中使用泛型类型加宽类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆