带有对象数组和接口的Typescript交集类型

时间:2017-08-16 15:10:27

标签: typescript types

我在理解交叉路口类型方面遇到了很多麻烦。这就是我所指的:

type FooList = Foo[] & {
    bar: string
};

interface Foo {
    baz: string;
}

经过大量的摆弄后,我无法创建FooList的类型数组。

这些类型不是我的,它们来自this library

这些类型是否意味着FooList必须是Foo的数组,并且还有一个对象bar?每个Foo对象是否必须包含属性bar

Here is the link to the playground

3 个答案:

答案 0 :(得分:2)

FooList既是Foo个对象的数组,也是包含字符串值bar属性的对象。

如果您愿意使用类型断言,那么创建一个就很容易,因为您可以告诉编译器您知道自己在做什么:

var foos: any; // turn off type checking
foos = [{ baz: 'baz1' }, { baz: 'baz2' }];
foos.bar = 'bar';
var fooList: FooList = foos as FooList; // assert type of fooList

创建其中一个安全,其中编译器保证您已经创建了正确类型的东西有点棘手,但您可以使用Object.assign()来执行此操作它的参数类型的交集:

const fooList: FooList = Object.assign([{ baz: 'baz' }, { baz: 'baz' }], { bar: 'bar' });

希望有所帮助。祝你好运!

更新1

@CésarAlbercasaid

  

谢谢!你的是我的首选解决方案。使用扩展运算符的对象分配的等价物是什么?

哦,当然,你可以这样做:

const fooList2: FooList = { ...[{ baz: 'baz' }, { baz: 'baz' }], ...{ bar: 'bar' } };

const fooList3: FooList = { ...[{ baz: 'baz' }, { baz: 'baz' }], bar: 'bar' };

干杯。

答案 1 :(得分:1)

FooList是一个数组Foo的数组,它还有一个名为bar的字符串属性。

以下是您创建它的方式:

function createFooList(bar: string, ...items: Foo[]): FooList {
    const arr = [] as FooList;
    arr.bar = bar;
    arr.push(...items);
    return arr;
}

或者:

function createFooList(bar: string, ...items: Foo[]): FooList {
    (items as FooList).bar = bar;
    return items as FooList;
}

答案 2 :(得分:0)

查看我的demo用法。

type LinkedList<T> = T & { next: LinkedList<T> };

interface Person {
    name: string;
}

var people: LinkedList<Person>;
var person: Person = { name: "Joey" };
var childPerson: Person = { name: "James" };
var grandChildPerson: Person = { name: "John" };

people = person;
people.next = childPerson;
people.next.next = grandChildPerson;

alert(JSON.stringify(people));

请参阅type aliases和交叉类型的打字稿文档