Multiple type signatures for members, Union Types in TypeScript

前端 未结 3 1342
失恋的感觉
失恋的感觉 2020-12-29 19:25

If I have a property that might be a string or a boolean how do I define it:

interface Foo{
    bar:string;
    bar:boolean;
}

I don\'t want

3条回答
  •  爱一瞬间的悲伤
    2020-12-29 19:57

    Not saying this answers your question, but could you resort to something like this?

    interface Foo{
        bar:T;
    }
    
    function createFoo(bar:T) : Foo{
        return {bar:bar};
    }
    
    var sFoo = createFoo("s");
    var len = sFoo.bar.length;
    
    var bFoo = createFoo(true);
    var result = bFoo.bar === true;
    

提交回复
热议问题