我在理解交叉点类型时遇到很多困难。这就是我所指的:
type FooList = Foo[] & {
bar: string
};
interface Foo {
baz: string;
}
Run Code Online (Sandbox Code Playgroud)
经过大量摆弄后,我无法创建FooList
.
这些打字不是我的,它们来自这个图书馆。
这些类型是否意味着FooList
必须是 s 数组Foo
并且还有一个对象bar
?每个Foo
对象都必须包含一个属性吗bar
?
AFooList
既是对象数组Foo
,也是包含字符串值bar
属性的对象。
如果您愿意使用类型断言,那么创建一个类型断言就很容易,因为您只需告诉编译器您知道自己在做什么:
\n\nvar foos: any; // turn off type checking\nfoos = [{ baz: \'baz1\' }, { baz: \'baz2\' }];\nfoos.bar = \'bar\';\nvar fooList: FooList = foos as FooList; // assert type of fooList\n
Run Code Online (Sandbox Code Playgroud)\n\n安全地创建其中一个东西,其中编译器保证您已经创建了正确类型的东西,这有点棘手,但是您可以使用 来做到这一点Object.assign()
,它返回其参数类型的交集:
const fooList: FooList = Object.assign([{ baz: \'baz\' }, { baz: \'baz\' }], { bar: \'bar\' });\n
Run Code Online (Sandbox Code Playgroud)\n\n希望有帮助。祝你好运!
\n\n请忽略下面的内容;我不确定我发生了什么,但是将数组分散到对象中不太可能按照任何人想要的方式工作,因为Array
原型方法不会被复制。只需使用上面的Object.assign()
解决方案即可。
@C\xc3\xa9sarAlberca说:
\n\n\n\n\n谢谢!你的解决方案是我的首选。使用展开运算符进行对象分配的等效项是什么?
\n
哦,当然,你可以这样做:
\n\nconst fooList2: FooList = { ...[{ baz: \'baz\' }, { baz: \'baz\' }], ...{ bar: \'bar\' } };\n
Run Code Online (Sandbox Code Playgroud)\n\n或者
\n\nconst fooList3: FooList = { ...[{ baz: \'baz\' }, { baz: \'baz\' }], bar: \'bar\' };\n
Run Code Online (Sandbox Code Playgroud)\n\n干杯。\n
归档时间: |
|
查看次数: |
5673 次 |
最近记录: |