Multiple type signatures for members, Union Types in TypeScript

前端 未结 3 1337
失恋的感觉
失恋的感觉 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:46

    As of 2015, union-types work:

    interface Foo {
        bar:string|boolean;
    }
    
    0 讨论(0)
  • 2020-12-29 19:50

    This is usually referred to as "union types". The TypeScript type system from 1.4 does allow for this.

    See: Advanced Types

    0 讨论(0)
  • 2020-12-29 19:57

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

    interface Foo<T>{
        bar:T;
    }
    
    function createFoo<T>(bar:T) : Foo<T>{
        return {bar:bar};
    }
    
    var sFoo = createFoo("s");
    var len = sFoo.bar.length;
    
    var bFoo = createFoo(true);
    var result = bFoo.bar === true;
    
    0 讨论(0)
提交回复
热议问题