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

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

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

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

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


当前回答

我很惊讶没有一个答案引用Object。赋值,因为这是我在考虑JavaScript中的“组合”时使用的技术。

在TypeScript中,它可以像预期的那样工作:

interface IExisting {
    userName: string
}

interface INewStuff {
    email: string
}

const existingObject: IExisting = {
    userName: "jsmith"
}

const objectWithAllProps: IExisting & INewStuff = Object.assign({}, existingObject, {
    email: "jsmith@someplace.com"
})

console.log(objectWithAllProps.email); // jsmith@someplace.com

优势

始终保持类型安全,因为您根本不需要使用任何类型 使用TypeScript的聚合类型(在声明objectWithAllProps类型时用&表示),这清楚地表明我们正在动态地(即动态地)组合一个新类型。

需要注意的事情

Object.assign has it's own unique aspects (that are well known to most experienced JS devs) that should be considered when writing TypeScript. It can be used in a mutable fashion, or an immutable manner (I demonstrate the immutable way above, which means that existingObject stays untouched and therefore doesn't have an email property. For most functional-style programmers, that's a good thing since the result is the only new change). Object.assign works the best when you have flatter objects. If you are combining two nested objects that contain nullable properties, you can end up overwriting truthy values with undefined. If you watch out for the order of the Object.assign arguments, you should be fine.

其他回答

当一个Map可以接受固定类型的任意值时,使用ES6 Map,否则使用可选属性

我想这就是我的指导方针。ES6映射可以在typescript中完成,如在typescript中提到的:ES6映射

可选属性的主要用例是函数的“选项”参数:使用命名参数JavaScript(基于typescript)在这种情况下,我们确实提前知道允许的属性的确切列表,所以最明智的事情是只定义一个显式接口,只是使任何可选的可选与?正如在https://stackoverflow.com/a/18444150/895245上提到的,尽可能多地进行类型检查:

const assert = require('assert')

interface myfuncOpts {
  myInt: number,
  myString?: string,
}

function myfunc({
  myInt,
  myString,
}: myfuncOpts) {
  return `${myInt} ${myString}`
}

const opts: myfuncOpts = { myInt: 1 }
if (process.argv.length > 2) {
  opts.myString = 'abc'
}

assert.strictEqual(
  myfunc(opts),
  '1 abc'
)

然后,当它是真正任意的(无限多个可能的键)并且具有固定类型时,我将使用Map,例如:

const assert = require('assert')
const integerNames = new Map<number, string>([[1, 'one']])
integerNames.set(2, 'two')
assert.strictEqual(integerNames.get(1), 'one')
assert.strictEqual(integerNames.get(2), 'two')

测试:

  "dependencies": {
    "@types/node": "^16.11.13",
    "typescript": "^4.5.4"
  }

通过将任何类型的对象类型转换为'any'来存储任何新属性:

var extend = <any>myObject;
extend.NewProperty = anotherObject;

稍后,你可以通过将扩展对象转换回'any'来检索它:

var extendedObject = <any>myObject;
var anotherObject = <AnotherObjectType>extendedObject.NewProperty;

案例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

只需这样做,您就可以添加或使用任何属性。(我使用的typescript版本为“typescript”:“~4.5.5”)

let contextItem = {} as any;

现在,您可以添加任何属性并在任何地方使用它。就像

contextItem.studentName = "kushal";

之后你可以这样使用它:

console.log(contextItem.studentName);

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