2017-01-23 39 views
2

讓我們下面的代碼:如何通過部分創建可擴展的類型而無需重複代碼?

interface A { 
    a: number; 
} 

// doesn't work - "An interface may only extend a class or another interface."  
// interface AOpt extends Partial<A> {} 

// does work, but leads to code duplication :(
interface AOpt { 
    a?: number; 
} 

interface B extends AOpt { 
    b: number; 
} 

如何在使用方式創建type接口Partial作品,但事實如此擴展,能夠通過一個接口?

+0

這是不可能的,但我需要類似的東西('Readonly <>')。 – Paleo

回答

1

看來我們需要將打字稿的下一個版本覆蓋,與拉請求"Allow deriving from object and intersection types"

type T1 = { a: number }; 
type T2 = T1 & { b: string }; 

// ... 

type Named<T> = T & { name: string }; 

interface N1 extends Named<T1> { x: string } // { a: number, name: string, x: string } 
interface N2 extends Named<T2> { x: string } // { a: number, b: string, name: string, x: string } 

interface P1 extends Partial<T1> { x: string } // { a?: number | undefined, x: string } 

the roadmap,它出現在標籤下混入「模式‘’以改善支持」,這被檢查。因此,應在[email protected]中提供。

相關問題