小编Jes*_*ess的帖子

TypeScript 类型转换

我有一个对象,在某些情况下我需要向它添加一些额外的属性。

interface Item {
    name: string
}

function addProp(obj: Item) {
    type WithFoo = Item & { foo?: string; }

    // The following does NOT work
    obj = obj as WithFoo;

    if (obj.name == 'test') {
        obj.foo = 'hello';
     }
}
Run Code Online (Sandbox Code Playgroud)

它似乎obj = obj as AnotherType不起作用,但如果我分配给另一个变量,它就会起作用const anotherObj = obj as AnotherType

有没有办法在不type引入另一个变量的情况下强制转换?

这里是网上游乐场

typescript typescript-typings

4
推荐指数
2
解决办法
2万
查看次数

标签 统计

typescript ×1

typescript-typings ×1