相关疑难解决方法(0)

如何在TypeScript中为对象动态分配属性?

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

var obj = {};
obj.prop = "value";
Run Code Online (Sandbox Code Playgroud)

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

类型"{}"的值不存在属性"prop"

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

typescript

291
推荐指数
16
解决办法
26万
查看次数

Dynamic key access in object literal results in widened typescript signature

For the following code:

const x = {
    a: 'c',
    b: 'd'
};

const y = {
    [x.a]: 'e',
}
Run Code Online (Sandbox Code Playgroud)

the generated types are:

typeof x -> {
    a: string,
    b: string
}

typeof y -> {
  [x: string]: string
}
Run Code Online (Sandbox Code Playgroud)

Expected type:

typeof y -> {
  c: string
}
Run Code Online (Sandbox Code Playgroud)

Similar issue on SO has a solution which is not relevant here

在Github上发现了已举报的问题,该问题已解决,但无法正常工作

typescript

5
推荐指数
1
解决办法
83
查看次数

标签 统计

typescript ×2