【问题标题】:Typescript joining key names/ string types打字稿加入键名/字符串类型
【发布时间】:2021-03-09 15:07:50
【问题描述】:

打字稿中有什么方法可以动态连接键名/动态连接字符串类型吗?我的意思是:

type JoinString<A extends string, B extends string> = /*some magic*/

const example = {
foo: "b",
bar: "c"
}

type GetAnotherKeys<T> = {
 JoinString<[TKey in keyof T], "_">: T[Tkey]
}

type Result = GetAnotherKeys<typeof example>;
/*
Result ={
foo_:string
bar_:string
}

*/





【问题讨论】:

    标签: javascript string typescript types


    【解决方案1】:

    这是一个简单的例子:

    type AddPrefix<T extends string>=`${T}_`
    
    type Keys={
       name:string;
       surname:string;
    }
    
    type MapPrefix<T>={
       [P in keyof T as AddPrefix<string & P>]:T[P]
    }
    
    type Result = MapPrefix<Keys>
    

    更多信息您可以找到here

    【讨论】:

    • 谢谢各位绅士,一周前的更新真是幸运
    • @MaciejDot 欢迎您。您可以接受这个答案,这将对其他人有所帮助
    猜你喜欢
    • 2018-07-18
    • 2022-01-03
    • 1970-01-01
    • 2018-04-28
    • 2022-10-25
    • 2023-02-10
    • 2021-08-20
    • 1970-01-01
    • 2016-10-25
    相关资源
    最近更新 更多