我在理解交叉点类型时遇到了很多麻烦。这就是我所指的:
type FooList = Foo[] & {
bar: string
};
interface Foo {
baz: string;
}
经过大量调整后,我无法创建 FooList
的类型化数组。
这些打字不是我的,它们来自this library .
这些类型是否意味着 FooList
必须是一个 Foo
数组并且还有一个对象 bar
?每个 Foo
对象都必须包含属性 bar
吗?
最佳答案
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/