【问题标题】:Is it possible to declare dynamic string type in Typescript [duplicate]是否可以在 Typescript 中声明动态字符串类型 [重复]
【发布时间】:2019-12-09 09:42:50
【问题描述】:

假设:

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 而不仅仅是字符串。

【问题讨论】:

标签: typescript


【解决方案1】:

对于那些仍然在这里找到自己的方式的人的更新:这将在 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#6579TypeScript#12754comment about this exact use case,但从 3.5.1 开始,答案是否定的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 2016-07-22
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多