如何使用另一种类型的属性中的类型

问题描述 投票:0回答:1

假设我有以下类型

type Person = {
  name: string,
  age: number,
  nicknames: string[],
}

我想从

Person
类型的属性类型创建另一种类型,所以它最终会像:

 type PersonTypes = string|number|string[]

我怎样才能做到这一点?

我尝试过使用 keyof 和 typeof 的变体,但我无法实现它。

typescript typescript-typings
1个回答
0
投票

你可以这样做:

type PersonTypes = Person[keyof Person]

如果您想要一个可以应用于任何类型的可重用泛型,您可以这样做:

type ValueOf<T> = T[keyof T]
type PersonTypes = ValueOf<Person>

游乐场链接

© www.soinside.com 2019 - 2024. All rights reserved.