TS获取对象属性值的类型

时间:2025-03-20 09:09:30

语法如下:

type Person = { age: number; name: string; alive: boolean };
 
type I2 = Person[keyof Person];
//type I2 = string | number | boolean

或者联合类型

const RestfulMethod = {
  get: 'GET',
  post: 'POST',
  put: 'PUT',
  delete: 'DELETE'
} as const


type IRestfulMethod = typeof RestfulMethod
type TypeRestfulMethod = IRestfulMethod[keyof IRestfulMethod]
// type TypeRestfulMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'

查看官方文档:/docs/handbook/2/

如果想获取对象属性名的类型,可以这样

type Person = { age: number; name: string; alive: boolean };
 
type I2 = keyof Person
//type I2 = 'age' | 'name' | 'alive'

把对象中的方法名取出来

let obj = {
  name: 'hello',
  age: 18, 
  eat () {
    return 'food'
  },
  link () {
    return 'dog'
  }
}

type methodsPick<T> = {[K in keyof T]: T[K] extends Function ? K : never}[keyof T];
// T1 = 'eat' | 'link'
type T1 = methodsPick<typeof obj>