gpt4 book ai didi

javascript - typescript 将字符串文字类型映射为大写

转载 作者:行者123 更新时间:2023-12-03 06:57:28 27 4
gpt4 key购买 nike

type a = 'one' | 'two'
我想要一个 type b喜欢
type b = 'ONE' | 'TWO'
所以我尝试了
type a = 'one' | 'two'
type b = {[P in a]: P['toUpperCase']}
但这并没有达到我想要的效果。
感谢您阅读:)

最佳答案

您现在可以在即将发布的 4.1 版本中执行此操作,并引入了 Template Literal Types。 :

type A = 'one' | 'two'
type B = `${Uppercase<A>}`

let b: B = 'one' // Type '"one"' is not assignable to type '"ONE" | "TWO"'.
TS Playground

关于javascript - typescript 将字符串文字类型映射为大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62581650/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com