我有一个对象,在某些情况下我需要向它添加一些额外的属性。
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引入另一个变量的情况下强制转换?
这里是网上游乐场