Typescript得到某个前缀开头的所有属性

229 阅读1分钟

如果有一个对象,它上面挂了很多get方法,比如

const obj={
    getName:()=>0,
    getId:()=>0,
    getSrc:()=>0,
    getTime:()=>0,
    getAge:()=>0,
    setAge:()=>0,
    //其他方法....
}

如果我想声明一个变量保存所有以get开头的属性,可以像下面这样操作

type GetMethods = (keyof typeof obj & `get${string}`)[]
//type GetMethods = ("getName" | "getId" | "getSrc" | "getTime" | "getAge")[]

写一个得到一个对象某个前缀开头的所有属性工具类型

type Keyof<O, Pre extends string> = keyof O & `${Pre}${string}`

使用一下

type Test = Keyof<typeof obj, 'get'>[]
type R = GetMethods extends Test ? true : false
// type R = true  ==>  GetMethods===Test