关于typescript遍历对象时,通过key-value形式赋值类型问题?
// n 和 addOrEditOptions都有可选属性,n包含addOrEditOptions所有属性rowDataChange(this: this, n: AddOrEditProductOptions) {
if (window.JSON.stringify(n) !== '{}') {
for (const key in this.addOrEditOptions) {
const k = key as keyof AddOrEditProductOptions //如何优雅的给key定义类型?
const value = n[k]
if (value) {
this.addOrEditOptions[k] = value // error: Type 'string' is not assignable to type 'never'.
}
}
}
//...
}
- 遍历对象时,如何给key定义类型?
- 通过key value 赋值,提示this.addOrEditOptions[k] 为never类型,如何解决?此处n 和 this.addOrEditOptions是同一个类型
目前我是通过this.addOrEditOptions[k] = value as never 取巧解决的
回复IanSun:
回答:
没看明白你这是要干啥?为啥要定义类型?
typescript">for (const key in this.addOrEditOptions) { n[key] && (this.addOrEditOptions[key] = n[key]);
}
直接赋值不就好了?还定义了一个中间变量 k
是要干啥的?
甚至于你这种合并两个对象的,用 Object.assign
不就好了?
回答:
interface AddOrEditProductOptions {}class Example {
private addOrEditOptions: AddOrEditProductOptions = {}
public rowDataChange<T extends AddOrEditProductOptions> (n: T) {
const { addOrEditOptions } = this;
let key: keyof T;
for (key in n) {
if (addOrEditOptions.hasOwnProperty(key)) {
addOrEditOptions[key as keyof AddOrEditProductOptions] = n[key as keyof AddOrEditProductOptions];
}
}
}
}
以上是 关于typescript遍历对象时,通过key-value形式赋值类型问题? 的全部内容, 来源链接: utcz.com/p/937528.html