2017-04-18 25 views
0

外部庫提供接口Foo與許多可選的屬性克隆接口:一些性質非可選

interface Foo { 
    propertyA?: string; 
    propertyB?: string; 
} 

我的代碼接受Foo並且在一些屬性的填充。後面的代碼要求這個部分填充的Foo

interface FooWithA { 
    propertyA: string; 
    propertyB?: string; 
} 

我可以使用哪些類型的註釋表示:「這是一個Foo與性能的X,Y,Z非可選」,使strictNullChecks停止抱怨?

回答

2

您可以使用intersection types

type FooWithA = Foo & { 
    propertyA: string; 
} 

,也可以擴展接口:

interface FooWithA extends Foo { 
    propertyA: string 
} 

如果你所擔心的是,編譯器抱怨null檢查,你可以使用這些時使用! non-null assertion operator屬性。

+0

我可以在不對propertyA的屬性類型進行硬編碼的情況下執行此操作嗎?聲明'FooWithA.propertyA'與'Foo.propertyA'具有相同的類型? – spiffytech

+0

我不認爲這是可能的。看看['! '非空斷言運算符](https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#non-null-assertion-operator)這可能解決您的問題'strictNullChecks'。 – Saravana