how to match string literal type when concat string in typescript

╄→гoц情女王★ 提交于 2019-12-18 09:45:57

问题


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

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

Is there any solutions to solve the problem here?

Thanks


回答1:


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

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).

Workaround now is to just your string values for 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.




回答2:


TypeScript will not infer a concatenated string to a custom type automatically so you'll have to infer it to TB manually:

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

See code snippet at CodeSandbox



来源:https://stackoverflow.com/questions/57653776/how-to-match-string-literal-type-when-concat-string-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!