Discriminate between empty object type and other concrete types

后端 未结 2 1604
轮回少年
轮回少年 2021-01-21 00:15

All of this compiles without error:

interface Empty { }
interface MaybeEmpty { a?: number; }

var one: Object = 20;
var two: Empty = 21;
var three: {} = 22;
var          


        
2条回答
  •  一个人的身影
    2021-01-21 01:17

    Necromancing.
    Had this problem myselfs.
    This is actually possible in TypeScript 2.2+.

    You need to add & object to your type-definition

    e.g.

    var varname: YourInterface & object = something;
    

    in your case:

    interface Empty { }
    interface MaybeEmpty { a?: number; }
    interface MaybeEmptyAndMore { a?: number; [x:string]: any; }
    
    
    var one: Object = 20;
    var two: Empty = 21;
    var three: {} = 22;
    var four: MaybeEmpty & object = 23;
    var foura: MaybeEmpty & object = {};
    var fourb: MaybeEmpty & object = { a: "23"};
    var fourc: MaybeEmpty & object = { abc: "23"};
    var fourd: MaybeEmptyAndMore & object = { abc: "123", def: "456" };
    

    By the way, if it could be a string or an interface (object), then:

    obj: string | YourInterface & object
    

    e.g.

    class Cookie
    {
        constructor(nameOrSettings: string | ICookieSettings  & object )
        {
            if(typeof(nameOrSettings)  === 'string')
            { do_something();}
            else if(typeof(nameOrSettings) === 'object')
            {
                 var obj:ICookieSettings = nameOrSettings;
            }
            else throw TypeError("foo");
        }
    }
    

提交回复
热议问题