如果我想在Javascript中以编程方式将一个属性分配给一个对象,我会这样做:
var obj = {};
obj.prop = "value";
但在TypeScript中,这会产生一个错误:
属性“prop”在类型为“{}”的值上不存在
我应该如何在TypeScript中分配任何新属性给对象?
如果我想在Javascript中以编程方式将一个属性分配给一个对象,我会这样做:
var obj = {};
obj.prop = "value";
但在TypeScript中,这会产生一个错误:
属性“prop”在类型为“{}”的值上不存在
我应该如何在TypeScript中分配任何新属性给对象?
当前回答
在TypeScript中动态地为对象分配属性。
你只需要像这样使用typescript接口:
interface IValue {
prop1: string;
prop2: string;
}
interface IType {
[code: string]: IValue;
}
你可以这样使用它
var obj: IType = {};
obj['code1'] = {
prop1: 'prop 1 value',
prop2: 'prop 2 value'
};
其他回答
我写过一篇文章探讨这个话题:
Typescript -在运行时增强对象及其类型
https://tech.xriba.io/2022/03/24/typescript-enhance-an-object-and-its-type-at-runtime/
也许你可以从Typescript概念中获得灵感,比如:
映射类型 通过as键重映射 十字路口类型
如果你正在使用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";
在TypeScript中动态地为对象分配属性。
你只需要像这样使用typescript接口:
interface IValue {
prop1: string;
prop2: string;
}
interface IType {
[code: string]: IValue;
}
你可以这样使用它
var obj: IType = {};
obj['code1'] = {
prop1: 'prop 1 value',
prop2: 'prop 2 value'
};
若要保留先前的类型,请将对象临时转换为any
var obj = {}
(<any>obj).prop = 5;
新的动态属性只有在使用强制转换时才可用:
var a = obj.prop; ==> Will generate a compiler error
var b = (<any>obj).prop; ==> Will assign 5 to b with no error;
试试这个:
export interface QueryParams {
page?: number,
limit?: number,
name?: string,
sort?: string,
direction?: string
}
然后使用它
const query = {
name: 'abc'
}
query.page = 1