首页 > 解决方案 > 打字稿界面中符号的计算键

问题描述

我正在尝试使此代码正常工作:

const userId: unique symbol = Symbol.for(`urn:${process.env.REACT_APP_ENV_VALUE}:claims/user-id`);

interface JwtPayload extends BaseJwtPayload {
  email: string;
  [userId]: string;
}

但是,console.log(userId)给出了值Symbol(urn:dev:claims/user-id)

我怎样才能实现以下目标:

interface JwtPayload extends BaseJwtPayload {
  email: string;
  [`urn:${process.env.REACT_APP_ENV_VALUE}:claims/user-id`]: string;
}

没有得到错误:

TS1169: A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.

标签: javascriptreactjstypescript

解决方案


我猜你的意思是这样的:

declare type REACT_APP_ENV_VALUE = "dev" | "production"

type Keys = `urn:${REACT_APP_ENV_VALUE}:claims/user-id`

type ABC = {    
    [key in Keys]: string
}

如有必要,您还可以添加问号,因此您的键是可选的:

type ABC = {    
    [key in Keys]?: string
}

示例用法:

const x : ABC = {
    "urn:dev:claims/user-id": "123"
}


alert(x['urn:dev:claims/user-id'])

这使用模板文字类型


推荐阅读