• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[Typescript]Dynamictypes:UseTypeScript'sMappedTypesandTemplateLiteralTypesTogeth ...

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

we're going to dive deep into a more complex example in which we combine mapped types, key remapping, template literal types, and indexed access types to statically type a highly dynamic JavaScript function in TypeScript.

Start with following code:

function createGetterObject(obj: any): any {
    const newObj: any = {};
    for (const key of Object.keys(obj)) {
        const cpK = key[0].toUpperCase() + key.substr(1);
        const getterKey = `get${cpK}`;
        newObj[getterKey] = () => obj[key];
    }
    return newObj;
}

const user = createGetterObject({
    name: "Wan",
    twitter: "zhentiw"
})

console.log(user)
console.log(user.getName())
console.log(user.getTwitter())

 

We want to get better typings support.

function createGetterObject<T>(obj: T): PropGetters<T> {
    const newObj: any = {};
    for (const key of Object.keys(obj)) {
        const cpK = key[0].toUpperCase() + key.substr(1);
        const getterKey = `get${cpK}`;
        newObj[getterKey] = () => obj[key];
    }
    return newObj;
}

type PropGetters<T> = {

}

Get an error:

This is because `T` can be any as well. We need to limit T type by telling that `T` can be only for Object:

function createGetterObject<T extends Record<string, any>>(obj: T): PropGetters<T> {

 

In `PropGetter`, we want to create similar to 

type PropGetters<T> = {
  getName: () => sting
  getTwitter: () => string
}

How to make those?

 

We can start from:

type PropGetters<T> = {
 [Key in keyof T]: () => T[Key]
}

keyof T: get all the keys of T, so we got `name` & `twitter`

T[Key]: as lookup type, `name` prop result in string `Wan`.

 

This is what we get as a result:

`name` & `twitter` are functions type which return string, not really what we want.

 

Template Literal Types

type PropGetters<T> = {
 [Key in keyof T as `get${Key}`]: () => T[Key]
}

Got error:

This is because Key can be string, number, boolean... , what we want is just string type, so we can do:

type PropGetters<T> = {
 [Key in string & keyof T as `get${Key}`]: () => T[Key]
}

Now, we got:

We actual want `getName` not as `getname`, to fix this, we can do:

type PropGetters<T> = {
 [Key in string & keyof T as `get${Capitalize<Key>}`]: () => T[Key]
}

 

Now the type should works. If we add another prop `id`:

Typescript can tell the return value is a number type.

 

Final piece to limit `T` in `PropGetters`:

type PropGetters<T extends Record<string, any>> = {
 [Key in string & keyof T as `get${Capitalize<Key>}`]: () => T[Key]
}

 

 

Read: https://egghead.io/lessons/typescript-use-typescript-s-mapped-types-and-template-literal-types-together


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
typescript类继承修饰符发布时间:2022-07-18
下一篇:
如何在typescript项目中调用js发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap