2017-04-13 110 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);