如果我想在Javascript中以编程方式将一个属性分配给一个对象,我会这样做:
var obj = {};
obj.prop = "value";
但在TypeScript中,这会产生一个错误:
属性“prop”在类型为“{}”的值上不存在
我应该如何在TypeScript中分配任何新属性给对象?
如果我想在Javascript中以编程方式将一个属性分配给一个对象,我会这样做:
var obj = {};
obj.prop = "value";
但在TypeScript中,这会产生一个错误:
属性“prop”在类型为“{}”的值上不存在
我应该如何在TypeScript中分配任何新属性给对象?
当前回答
只需这样做,您就可以添加或使用任何属性。(我使用的typescript版本为“typescript”:“~4.5.5”)
let contextItem = {} as any;
现在,您可以添加任何属性并在任何地方使用它。就像
contextItem.studentName = "kushal";
之后你可以这样使用它:
console.log(contextItem.studentName);
其他回答
当对象具有特定类型时,此解决方案非常有用。比如从其他源获取对象时。
let user: User = new User();
(user as any).otherProperty = 'hello';
//user did not lose its type here.
案例1:
var car = {type: "BMW", model: "i8", color: "white"};
car['owner'] = "ibrahim"; // You can add a property:
案例2:
var car:any = {type: "BMW", model: "i8", color: "white"};
car.owner = "ibrahim"; // You can set a property: use any type
唯一完全类型安全的解决方案是这个,但是有点啰嗦,并且迫使您创建多个对象。
如果你必须先创建一个空对象,那么从这两个解决方案中选择一个。记住,每次你使用as,你就失去了安全。
安全解决方案
对象类型在getObject中是安全的,这意味着对象。A的类型为字符串| undefined
interface Example {
a: string;
b: number;
}
function getObject() {
const object: Partial<Example> = {};
object.a = 'one';
object.b = 1;
return object as Example;
}
短期解决方案
对象类型在getObject中是不安全的,这意味着对象。即使在赋值之前,A的类型也是string。
interface Example {
a: string;
b: number;
}
function getObject() {
const object = {} as Example;
object.a = 'one';
object.b = 1;
return object;
}
如果你正在使用Typescript,你可能想要使用类型安全;在这种情况下,naked Object和'any'是相反的。
最好不要使用Object或{},而是使用一些命名类型;或者您可能正在使用具有特定类型的API,您需要使用自己的字段进行扩展。我发现这个方法很有效:
class Given { ... } // API specified fields; or maybe it's just Object {}
interface PropAble extends Given {
props?: string; // you can cast any Given to this and set .props
// '?' indicates that the field is optional
}
let g:Given = getTheGivenObject();
(g as PropAble).props = "value for my new field";
// to avoid constantly casting:
let k = getTheGivenObject() as PropAble;
k.props = "value for props";
另一个方法是将属性作为一个集合来访问:
var obj = {}; obj['prop'] = “值”;