2015-10-14 76 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!"}; 
相關問題