Typescript 替换/引用字符串常量时出错
我试图使用不同类型脚本文件中的字符串常量作为映射类型中的键 下面是一个简单的例子:Typescript 替换/引用字符串常量时出错,typescript,Typescript,我试图使用不同类型脚本文件中的字符串常量作为映射类型中的键 下面是一个简单的例子: src/common/model constants.ts export default class Constants { public static readonly KEY_PREFIX: string = "x"; } export interface AProps { readonly key: { [key: string]: string; }; } im
src/common/model constants.ts
export default class Constants {
public static readonly KEY_PREFIX: string = "x";
}
export interface AProps {
readonly key: {
[key: string]: string;
};
}
import Constants from "./common/model-constants";
import AProps from "./models/prop";
const prop: AProps = {
a: "1"
};
const prop2: AProps = {
Constants.KEY_PREFIX : "2"
}
const prop3: AProps.key = {};
prop3[Constants.KEY_PREFIX] = "3";
src/models/prop.ts
export default class Constants {
public static readonly KEY_PREFIX: string = "x";
}
export interface AProps {
readonly key: {
[key: string]: string;
};
}
import Constants from "./common/model-constants";
import AProps from "./models/prop";
const prop: AProps = {
a: "1"
};
const prop2: AProps = {
Constants.KEY_PREFIX : "2"
}
const prop3: AProps.key = {};
prop3[Constants.KEY_PREFIX] = "3";
src/index.ts
export default class Constants {
public static readonly KEY_PREFIX: string = "x";
}
export interface AProps {
readonly key: {
[key: string]: string;
};
}
import Constants from "./common/model-constants";
import AProps from "./models/prop";
const prop: AProps = {
a: "1"
};
const prop2: AProps = {
Constants.KEY_PREFIX : "2"
}
const prop3: AProps.key = {};
prop3[Constants.KEY_PREFIX] = "3";
prop
和prop3
可以工作,但是prop2
不能使用
/src/index.ts: Unexpected token (12:4)
10 | var prop2 = {
11 | Constants: model_constants_1.default,
> 12 | : .KEY_PREFIX, "2":
| ^
13 | };
14 | var prop3 = {};
15 | prop3[model_constants_1.default.KEY_PREFIX] = "3";
在codesandbox中有同样的东西:
为什么直接在映射文本中引用字符串类型常量不起作用?为什么我会在错误控制台中看到
model\u constants\u 1.default
const prop2:AProps={
[常数.键前缀]:“2”
}
也可以考虑更改<代码> ApPrs<代码>声明或将<代码>键<代码>属性添加到您的对象:
类常量{
公共静态只读密钥\u前缀:string=“x”;
}
接口AProps{
只读键:{
[键:字符串]:字符串;
};
}
常量属性:AProps={
关键:{
a:“1”
}
};
常数建议2:AProps={
关键:{
[常数.键前缀]:“2”
}
}
常量prop3:AProps={key:{};
prop3.key[常数.key_前缀]=“3”;
您尝试执行的操作被称为,并且是这样写的:
const prop2:AProps={
[常数.键前缀]:“2”
}
也可以考虑更改<代码> ApPrs<代码>声明或将<代码>键<代码>属性添加到您的对象:
类常量{
公共静态只读密钥\u前缀:string=“x”;
}
接口AProps{
只读键:{
[键:字符串]:字符串;
};
}
常量属性:AProps={
关键:{
a:“1”
}
};
常数建议2:AProps={
关键:{
[常数.键前缀]:“2”
}
}
常量prop3:AProps={key:{};
prop3.key[常数.key_前缀]=“3”;
要使用计算值作为对象键,需要使用尖括号[]
为了使用计算值作为对象键,需要使用尖括号[]
现在还不完全清楚您的意图是什么,但我花了时间尽可能地修复了您的代码…:@spender感谢您花时间修复错误,但我想我已经注释掉了问题中出现错误的部分。你能从你的沙盒链接中取消注释
index.ts
中的第8行、第9行和第10行吗?我的问题是关于什么的?你的意图并不完全清楚,但我花了时间尽我所能修复了你的代码…:@spender感谢您花时间修复错误,但我想我已经注释掉了问题中出现错误的部分。你能从沙盒链接中取消注释index.ts中的第8、9和10行,看看我的问题是关于什么的吗?