在打字稿中使用concat字符串时如何匹配字符串文字类型 [英] how to match string literal type when concat string in typescript

查看:96
本文介绍了在打字稿中使用concat字符串时如何匹配字符串文字类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

type TA = 'App' | 'Area';
type TB = 'getAppDetail' | 'getAreaDetail';
const a: TA = 'App';
const b: TB = `get${a}Detail`;

但是get${a}Detail返回字符串类型.而且它与TB类型不匹配.

But get${a}Detail returns a string type. And it doesn't match type TB.

这里有解决问题的解决方案吗?

Is there any solutions to solve the problem here?

谢谢

推荐答案

您想要的可能类似于经过正则表达式验证的字符串类型.目前,不幸的是,两者都不可能.

What you want is probably something like a string literal expression type or Regex-validated string type. Currently both are not possible unfortunately.

类型系统需要可静态分析-在您的示例中,您有一个简单的字符串表达式get${a}Detail,但是如果您调用一个可能的async函数来生成您的${a}字符串或执行其他动态操作,该怎么办?级联?这将很难分析,甚至不可能.根据第一个问题,正则表达式类型有较高的实现机会(并且具有GitHub上的体面讨论活动).

The type system requires to be statically analyzable - in your example, you have a simple string expression get${a}Detail, but what if you for example invoke a possibly async function to generate your ${a} string or do other dynamic concatenations? That will be hard to analyze or even not be possible. According to the first issue, regex types have a higher chance of getting implemented (and have decent discussion activity on GitHub).

现在的解决方法是直接将字符串值设置为TATB类型.如果使用其他类型(例如对象文字)要缩小其字符串属性,则可以使用

Workaround now is to just set your string values to TA and TB type directly. If you use other types like object literals whose string properties you want to have narrowed, you can used as const assertions.

这篇关于在打字稿中使用concat字符串时如何匹配字符串文字类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆