打字稿:有没有办法将某些内容限制为 javascript 'object' 类型?
Typescript: is there a way to restrict something to just a javascript 'object' type?
我原以为使用 Object
类型就可以了,但这仍然允许任何事情。我想要这样的东西:
function foo(arg: /* what goes here? */) { }
foo({}) // should compile
foo({ something: 'anything'}) // should compile
foo(new Object()) // should compile
foo(7) // should not compile
foo('hello') // should not compile
无法在 TypeScript 1.4 的编译时设置 Javascript Object
类型约束。但是您仍然可以在 运行 时间检查类型。
function foo(arg: Object) {
if (typeof arg !== "object") { throw new Error("Error"); }
console.log(arg);
}
我原以为使用 Object
类型就可以了,但这仍然允许任何事情。我想要这样的东西:
function foo(arg: /* what goes here? */) { }
foo({}) // should compile
foo({ something: 'anything'}) // should compile
foo(new Object()) // should compile
foo(7) // should not compile
foo('hello') // should not compile
无法在 TypeScript 1.4 的编译时设置 Javascript Object
类型约束。但是您仍然可以在 运行 时间检查类型。
function foo(arg: Object) {
if (typeof arg !== "object") { throw new Error("Error"); }
console.log(arg);
}