如果我想在Javascript中以编程方式将一个属性分配给一个对象,我会这样做:

var obj = {};
obj.prop = "value";

但在TypeScript中,这会产生一个错误:

属性“prop”在类型为“{}”的值上不存在

我应该如何在TypeScript中分配任何新属性给对象?


当前回答

我在尝试对作为状态存储的对象进行部分更新时遇到了这个问题。

type State = {
  foo: string;
  bar: string;
  baz: string;
};

const newState = { foo: 'abc' };

if (someCondition) {
  newState.bar = 'xyz'
}

setState(newState);

在这种情况下,最好的解决方案是使用Partial<T>。方法使所提供类型上的所有属性都是可选的。令牌。在更具体的SO主题中阅读更多关于使类型上的所有属性都是可选的。

以下是我如何用Partial<T>解决它:

type State = {
  foo: string;
  bar: string;
  baz: string;
};

const newState: Partial<State> = { foo: 'abc' };

if (someCondition) {
  newState.bar = 'xyz';
}

setState(newState);

这与fregante在他们的回答中描述的类似,但我想为这个特定的用例描绘一个更清晰的画面(这在前端应用程序中很常见)。

其他回答

如果你正在使用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";

您可以添加此声明来屏蔽警告。

declare var obj: any;

这是Object的一个特殊版本。赋值,它会在每次属性更改时自动调整变量类型。不需要额外的变量、类型断言、显式类型或对象副本:

function assign<T, U>(target: T, source: U): asserts target is T & U {
    Object.assign(target, source)
}

const obj = {};
assign(obj, { prop1: "foo" })
//  const obj now has type { prop1: string; }
obj.prop1 // string
assign(obj, { prop2: 42 })
//  const obj now has type { prop1: string; prop2: number; }
obj.prop2 // number

//  const obj: { prop1: "foo", prop2: 42 }

注意:示例使用TS 3.7断言函数。与Object.assign不同,assign的返回类型是void。

在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' 
};

可以通过将成员添加到现有对象

扩大类型(读取:扩展/专门化接口) 将原始对象转换为扩展类型 将成员添加到对象中

interface IEnhancedPromise<T> extends Promise<T> {
    sayHello(): void;
}

const p = Promise.resolve("Peter");

const enhancedPromise = p as IEnhancedPromise<string>;

enhancedPromise.sayHello = () => enhancedPromise.then(value => console.info("Hello " + value));

// eventually prints "Hello Peter"
enhancedPromise.sayHello();