带有对象数组和接口(interface)的 typescript 交集类型

标签 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

最佳答案

A FooList都是 Foo 的数组对象,以及包含字符串值 bar 的对象属性(property)。

如果您愿意使用类型断言,那么创建一个就足够简单了,因为您只需告诉编译器您知道自己在做什么:

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' });

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


请忽略下面的内容;我不确定我是怎么想的,但是将一个数组散布到一个对象中不太可能像任何人想要的那样工作,因为 Array原型(prototype)方法不会被复制。只需使用上面的 Object.assign()解决方案。

<罢工>

<罢工>

更新 1

@CésarAlberca said :

Thanks! Yours was my preferred solution. What is the equivalent of object assign using the spread operator?

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

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

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

干杯。

关于带有对象数组和接口(interface)的 typescript 交集类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45717246/

相关文章:

Hibernate 类型和 JBoss 兼容性问题

javascript - 通过 webpack 生产模式编译时如何忽略 typescript 错误

使用管道或其他方式对数据进行 Angular 美化

c# - .NET C# float.Parse 将不同的结果返回给 double.Parse

java - 为什么使用 == 比较两个整数有时有效有时无效?

go - 如何将字节数组传递给接受字节 slice 的函数?

typescript - 如何根据字段值省略联合类型

c# - 将值从 Angular 服务应用程序发送到 C# 后端 Controller

angular - Angular 的组件名称相同

asp.net - 类型上的问号