TypeScript type cast

前端 未结 3 626
孤城傲影
孤城傲影 2021-01-24 12:47

I have an object, and I need to add some extra properties to it in some cases.

interface Item {
    name: string
}

functi         


        
3条回答
  •  甜味超标
    2021-01-24 13:26

    obj = obj as WithFoo does not work because the type of obj is Item and you want to store in it an object of type WithFoo.

    But you can use another variable of type WithFoo and store obj in it. Because obj is an object, both variables will keep references to the same data:

    interface Item {
        name: string
    }
    
    function addProp(obj: Item) {
        type WithFoo = Item & { foo?: string; }
        const foo = obj as WithFoo;
        if (obj.name == 'test') {
            foo.foo = 'hello';
         }
    }
    
    const x1: Item = { name: 'test' }
    addProp(x1);
    console.log(x1);
    
    const x2: Item = { name: 'not-matching' }
    addProp(x2);
    console.log(x2);
    

    Try it online.

提交回复
热议问题