嵌套选择对象属性

时间:2017-04-13 19:31:17

标签: typescript typescript2.1

我有一些看起来像这个简化示例的代码:

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来定义我的函数所需的确切属性吗?

1 个答案:

答案 0 :(得分: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);