在打字稿中连接字符串时如何匹配字符串文字类型
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`;
但是get${a}Detail
returns一个字符串类型。而且它与 TB 类型不匹配。
这里有解决问题的方法吗?
谢谢
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 不会自动将连接的字符串推断为自定义类型,因此您必须手动将其推断为 TB
:
type TA = 'App' | 'Area';
type TB = 'getAppDetail' | 'getAreaDetail';
const a: TA = 'App';
const b = `get${a}Detail` as TB;
type TA = 'App' | 'Area';
type TB = 'getAppDetail' | 'getAreaDetail';
const a: TA = 'App';
const b: TB = `get${a}Detail`;
但是get${a}Detail
returns一个字符串类型。而且它与 TB 类型不匹配。
这里有解决问题的方法吗?
谢谢
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 不会自动将连接的字符串推断为自定义类型,因此您必须手动将其推断为 TB
:
type TA = 'App' | 'Area';
type TB = 'getAppDetail' | 'getAreaDetail';
const a: TA = 'App';
const b = `get${a}Detail` as TB;