2015-10-14 62 views
0

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

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); 

回答

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; 
1

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

解决方法

只允许类型要允许(而非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!"}; 
相关问题