javascript - 打字稿界面中符号的计算键
问题描述
我正在尝试使此代码正常工作:
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.
解决方案
我猜你的意思是这样的:
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'])
这使用模板文字类型
推荐阅读
- ios - API 不接受 SHA1 哈希
- laravel - 使用 Laravel for Stripe 发出 OAuth 请求
- google-apps-script - 将 Google 表格作为 HTML 表格发布到 Google 站点
- javascript - 寻找 fetch js/css 解决方案
- reactjs - React Firebase 退出
- php - Restful PHP,方法 POST 获取参数
- apache-spark-sql - 如何在 spark sql 中使用过滤器获取费率:Struct to get BGN,BRL in range between (2019-01-02 , 2019-01-04)
- angular - 如何在指令中使用 ngx translate
- c# - 如何使用 C# 的管理员权限启动 PowerShell?
- javascript - 在 Gatsby 中查询子节点字段