[英]Computed Key from Symbol in Typescript Interface
I'm trying to make this code work:我正在尝试使此代码正常工作:
const userId: unique symbol = Symbol.for(`urn:${process.env.REACT_APP_ENV_VALUE}:claims/user-id`); interface JwtPayload extends BaseJwtPayload { email: string; [userId]: string; }
However, console.log(userId)
gives the value Symbol(urn:dev:claims/user-id)
.但是,
console.log(userId)
给出了值Symbol(urn:dev:claims/user-id)
。
How can I achieve the following:我怎样才能实现以下目标:
interface JwtPayload extends BaseJwtPayload { email: string; [`urn:${process.env.REACT_APP_ENV_VALUE}:claims/user-id`]: string; }
without getting the error:没有得到错误:
TS1169: A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.
I guess you mean something like the following:我猜你的意思是这样的:
declare type REACT_APP_ENV_VALUE = "dev" | "production"
type Keys = `urn:${REACT_APP_ENV_VALUE}:claims/user-id`
type ABC = {
[key in Keys]: string
}
If necessary, you could also add a questionmark, so your keys are optional:如有必要,您还可以添加问号,因此您的键是可选的:
type ABC = {
[key in Keys]?: string
}
Example usage:示例用法:
const x : ABC = {
"urn:dev:claims/user-id": "123"
}
alert(x['urn:dev:claims/user-id'])
This uses Template Literal Types这使用模板文字类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.