简体   繁体   English

TypeScript:声明一个具有对象文字类型的变量

[英]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: 我正在尝试为应该只接受引用类型而不接受原语的函数找到正确的签名(TypeScript的当前版本为1.7):

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. 如果您觉得辛苦,可以添加它 ,因为项目正在接受对此功能的请求请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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