2017-04-13 120 views
0

我有一些代碼,看起來像這樣簡單的例子:對象屬性的嵌套匹克

interface Foo { 
    x: string; 
    y: string; 
} 

interface Bar { 
    a: string; 
    b: number; 
    foo: Foo 
} 

function printStuff(bar: Bar) { 
    console.log(bar.a); 
    console.log(bar.foo.x); 
} 

在我的單元測試,我要要調用printStuff與最低限度參數:{a: 'someval', foo: {x: 1}}。我不想爲FooBar構建完整參數集的對象。

我知道我能寫的printStuff參數簽名作爲一個匿名接口,但隨後的斷開連接從發生到FooBar任何變化。如果我使用參數中的更多屬性,它可能會變得冗長。

我可以改爲使用Pick來定義我的函數的確切屬性?

+0

退房'Partial' 。 – 2017-04-16 09:19:21

回答

0

有幾種方法可以用typeinterface進行切片和切塊。

這裏有一個精細的方法,避免匿名性和維持關係:

interface FooX { x: number; } 
interface FooY { y: number; } 

interface BarA { a: string; } 
interface BarB { b: string; } 

interface SlimBar extends BarA { 
    foo: FooX; 
} 

interface Foo extends FooX, FooY {} 

interface Bar extends BarA, BarB { 
    foo: Foo; 
} 

function printStuff(bar: SlimBar) { 
    console.log(bar.a); 
    console.log(bar.foo.x); 
} 

const stuff = { a: 'someval', foo: { x: 1 } }; 
printStuff(stuff); 

Try it in TypeScript Playground

或者你可以跳過額外的類型和投爲any

function printStuff(bar: Bar) { 
... 
printStuff(stuff as any);