简体   繁体   中英

TypeScript: Declare a variable with type of object literal

I am trying to find proper signature (current version of TypeScript is 1.7) for function that should accept only reference types, not primitives:

function onlyObject(x: ???) {
    if (typeof x !== 'object') {
        throw "bad arg!";
    }
}

So for function above this should work:

onlyObject({ });
onlyObject(new Date());
onlyObject(new Number(1));
onlyObject(null);
onlyObject(function () { });

but this will fail in compile time:

onlyObject("awd");
onlyObject(1);
onlyObject(false);

There currently isn't a way to express this in the language.

If you're feeling industrious, you can add it , as the project is accepting pull requests for this feature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM