假设:
export enum EEnv { devint, qa1 };
export type TEnv = keyof typeof EEnv;
export const env:Record<TEnv, {something:number}> = {
devint: {
something: 1,
},
qa1: {
something: 1,
},
}
然后我想创建基于env
对象的动态对象,像这样:
export const SAVE_TOKEN: Record<TEnv, string> = {
devint: "SAVE_TOKEN/devint", // based on "env" key
qa1: "SAVE_TOKEN/qa1", // based on "env" key
}
是否有任何方法可以将字符串类型创建为 "SAVE_TOKEN/"+TEnv
而不仅仅是字符串。
最佳答案
对于那些仍然在这里找到自己的方式的人的更新:这将在 4.1 中添加,请参阅 TypeScript#40336 .
export type SaveTokenNamespace<K extends string> = { [T in K]: `SAVE_TOKEN/${T}` };
export function makeNamespace<K extends TEnv>(env: Record<K, unknown>): SaveTokenNamespace<K> {
return Object.keys(env).reduce((ns, k) => ({ ...ns, [k]: `SAVE_TOKEN/${k}` }), {} as SaveTokenNamespace<K>);
}
console.log(makeNamespace(env));
const envNamespace = makeNamespace(env);
const test1: 'SAVE_TOKEN/qa1' = envNamespace.qa1; // Ok!
const test2: 'SAVE_TOKEN/notqa1' = envNamespace.qa1; // Error: Type '"SAVE_TOKEN/qa1"' is not assignable to type '"SAVE_TOKEN/notqa1"'.
Try it in the TypeScript playground
有一些受欢迎的开放提案/请求,包括 Regex-validated string type: TypeScript#6579和 TypeScript#12754与 comment about this exact use case ,但从 3.5.1 开始,答案是否定的。
关于typescript - 是否可以在 Typescript 中声明动态字符串类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57298071/