2017-01-11 14 views
1

我有以下代碼:如何告訴TypeScript對象中的可選屬性是否存在並被設置?

interface First 
{ 
    propertyA: string; 
} 

// Here propertyA is optional 
// Imagine that this interface came from external library. 
interface Second 
{ 
    propertyA ?: string; 
} 

function fn(arg: First) 
{ 
    // ... 
} 

// I know that this object can be declared as type of First, 
// but I really need set this as type of Second interface 
let myVar: Second = {propertyA: 'some string'}; 

// I really need in this way to make the call. 
fn(myVar); // Error 

if(myVar.hasOwnProperty('propertyA')) 
{ 
    fn(myVar); // Still same error 
} 

if(myVar.propertyA) 
{ 
    fn(myVar); // Still same error 
} 

但打字稿扔錯誤:

Argument of type 'Second' is not assignable to parameter of type 'First'. Property 'propertyA' is optional in type 'Second' but required in type 'First'.

那麼,如何告訴在myVar可選屬性propertyA存在並設置打字稿?

回答

0

我不明白你爲什麼聲明它爲Second,因爲它有屬性。但是,您可以執行下列操作之一:

  • 變化的宣言的First類型,即let myVar: First = {propertyA: 'some string'};
  • 完全刪除該類型聲明。然後,它會收到一個匿名類型{ propertyA: string; },將可分配給First,即let myVar = {propertyA: 'some string'};
  • 使用顯式類型轉換,即fn(<First>myVar);

的錯誤造成的,因爲它不是安全承擔可選屬性將在那裏。

+0

如果你認真對待我的問題,那麼也許它會更容易理解。例如,如果我使用外部庫,我不能更改'interface Second'的定義,但它仍然與'interface First'兼容。 – ktretyak

+0

問題是由於可選屬性,接口'Second'與接口'First'不兼容。無論如何,我提出的所有3種解決方案都適用於這種情況。 –

1

你可以這樣做:

fn(myVar as First); 

,並使用type guard的,如果:

function isFirst(obj: any): obj is First { 
    return obj && obj.propertyA; 
} 

if(isFirst(myVar)) { 
    fn(myVar); 
} 
+0

謝謝,我知道類型後衛,但其工作有點不同的目的,因爲我不需要檢查類型的參數。我有兩個兼容的對象,我相信這是存在的方式來澄清TypeScript的這一事實。 – ktretyak

+0

但它們不兼容。 「{a:any}」與「{a?:any}」不是同一種類型。除了type assert或type guard之外,您無法澄清該編譯器。 –

相關問題