typescript - 将字符串转换为对象属性名称
问题描述
我已经看到一个类似的问题询问这个关于 javascript 的问题。但是,我需要打字稿中的答案,但我不知道该怎么做。将字符串值转换为对象属性名称
let madeObject = {};
const fieldName = 'title';
madeObject[fieldName] = 'hello';
此外,我正在尝试创建一个接口,string[]
其中每个元素都是具有所需属性名称和值类型的字符串。使用数组元素设置新对象的字段。正因为如此,我事先不会知道我的属性将是什么,因此我为什么要尝试找到一种方法来创建具有给定属性的新接口。
解决方案
那是因为 typescript 推断出的类型madeObject
是{}
(空对象)。只需给它一个更明确的类型
interface MyObject {
title:string;
}
let madeObject:Partial<MyObject> = {};
const fieldName:keyof MyObject = 'title';
madeObject[fieldName] = 'hello';
如果你知道一个对象会有键,但你不知道键的名称(可能是因为它们只在运行时才知道),那么你可以使用 typescripts 动态键
interface MyObject {
// left side is the type of the key (usually string or symbol)
// right side is the type of the property (use "any" if you don't know)
[key:string]: string;
}
let madeObject:MyObject = {};
const fieldName:string = 'title';
madeObject[fieldName] = 'hello';
// Or you can make the interface Generic, if you have this situation a lot:
interface MyObjectGeneric <V = any, K = string> {
[key:K]: V;
}
let madeObject:MyObjectGeneric/* <string> */ = {}; // Adding <string> would narrow the return type down to string
const fieldName:string = 'title';
madeObject[fieldName] = 'hello';
解决此问题的另一种方法是一起删除类型安全(不推荐这样做,并且会使打字稿失去其用途)
let madeObject:any = {}; // declares that madeObject could be anything
const fieldName = 'title';
madeObject[fieldName] = 'hello';
// alternatively:
let madeObject2 = {}; // Type inferred as "{}"
(madeObject2 as any)[fieldName] = 'hello'; // Removes type safety only temporarily for this statement
推荐阅读
- html - jQuery:不是按升序和降序排序,而是简单地做一个反转
- javascript - 为什么变量 'a' 无法访问 document.querySelector('#b1').value 的新值
- azure - 为 AAD B2C 应用程序委派权限或让客户端应用程序请求范围
- javascript - 提交表单后清除字段弹出字段必填消息
- arrays - Perl中如何将一个数组分成两个不同的数组
- java - Apache Spark 的大量列名称中包含模式的错误记录
- javascript - 如何在 highchart 中使用下面的 fillOpacity 到 PlotLine?
- python - 如何动态拟合作物植物的 sigmoid 生长曲线?
- r - R中的循环命令
- string - 如何转换 Vec
到 &[&str]?