打字稿可以表达“一个是某种对象”吗?

时间:2015-10-14 21:48:58

标签: typescript

在下面的代码片段中,TypeScript可以表达“a是某个对象,但不是布尔,数字,字符串,数组或函数”吗?

var a:Object;
a = {
    just: "some object",
    n: 1,
};
// what type does `a` need to disallow the following
a = ["array", 2, {}];
a = "nostring";
a = false;
a = 0;
a = ()=> { return "i am a function!"};
var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(a.toString());
};

document.body.appendChild(button);

3 个答案:

答案 0 :(得分:1)

  

a是某个对象,但不是布尔值,数字,字符串,数组或函数

没有。

解决方法

仅允许您要允许的类型(而不是catchall Object)。如果您愿意,可以使用联合类型:

// Only allow the things you want: 
let b : {
    just:string;
    n: number
} | {
    foo:string;
    bar: string;
};

b = {
    just: "some object",
    n: 1,
};

b = {
    foo: 'hello',
    bar: 'world'
}
// All the following are errors: 
b = ["array", 2, {}];
b = "nostring";
b = false;
b = 0;
b = ()=> { return "i am a function!"};

答案 1 :(得分:1)

这有效...但请不要实际使用它。类型应该定义什么是什么,而不是它不是什么。

interface Array<T> { notArray: void; }
interface String   { notString: void; }
interface Boolean  { notBoolean: void; }
interface Number   { notNumber: void; }
interface Function { notFunction: void; }

interface GuessWhatIam {
    notArray?: string;
    notString?: string;
    notBoolean?: string;
    notNumber?: string;
    notFunction?: string;
    [key: string]: any;
}

var a: GuessWhatIam;

答案 2 :(得分:0)

创建自己的ObjectLiteral接口

export interface ObjectLiteral {
   [prop: string]: any
}

const a: ObjectLiteral = {
    just: "some object",
    n: 1,
};

enter image description here