[英]how to match string literal type when concat string in typescript
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.但是
get${a}Detail
返回一个字符串类型。 And it doesn't match type TB.它与类型 TB 不匹配。
Is there any solutions to solve the problem here?这里有解决问题的方法吗?
Thanks谢谢
This is possible with TypeScript 4.1 Template Literal Types + const assertions / as const
:这可以通过 TypeScript 4.1 Template Literal Types + const assertions /
as const
:
// given
type TA = 'App' | 'Area';
type TB = 'getAppDetail' | 'getAreaDetail';
const a: TA = 'App';
const aError = 'Nap';
// tests
const bInferred = `get${a}Detail` as const; // "getAppDetail"
const bChecked: TB = `get${a}Detail` as const; // works
const bChecked_Error: TB = `getNapDetail`; // error
const bChecked_Error2: TB = `get${aError}Detail` as const; // error
TypeScript will not infer a concatenated string to a custom type automatically so you'll have to infer it to TB
manually: TypeScript 不会自动将连接字符串推断为自定义类型,因此您必须手动将其推断为
TB
:
type TA = 'App' | 'Area';
type TB = 'getAppDetail' | 'getAreaDetail';
const a: TA = 'App';
const b = `get${a}Detail` as TB;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.