另一个推断问题。当我将联合类型埋在对象中时,我试图防止Typescript丢失正确推断的类型信息。情况如下:
Foo和Moo这两个接口及其联合FooMoo:
interface Foo { goo: string}
interface Moo { goo: number}
type FooMoo = Foo | Moo
const foo: Foo = {goo: "bar"}
const moo: Moo = {goo: 1}
以及一个包含(至少)每个对象的混合对象:
const mixedObject = {
foo,
moo
}
现在,很明显,TS知道foo和moo的正确类型,因此这里没有问题:
let fooToo: Foo
let mooToo: Moo
fooToo = mixedObject.foo
mooToo = mixedObject.moo
但是现在让我告诉TS,mixedObject应该仅限于 foos和moos。好吧,这种限制显然导致TS失去了区分foo和moo的能力,因此出现以下代码错误:
type ManyFooMoos = {[K:string]: FooMoo}
const mixedObjectToo: ManyFooMoos = {
foo,
moo
}
// TS errors here because it can't narrow foo to Foo and moo to Moo;
// it just knows they are both FooMoos
fooToo = mixedObjectToo.foo
mooToo = mixedObjectToo.moo
同一件事可以通过其他方式出现,其中导致TS丢失信息的MixedObject约束更为间接。例如:
interface ExportedObject {
manyFooMoos: ManyFooMoos
}
const exportedObject: ExportedObject = {
manyFooMoos: mixedObject
}
fooToo = exportedObject.manyFooMoos.foo
所以,我的基本问题是-如何保持对mixedObject的约束(即,其所有属性必须是Foos或Moos)而又不丢失混合对象内的那些Foos或Moos的类型是什么?
完整代码位于this playground上。
答案 0 :(得分:3)
您可以通过使用身份函数+泛型来实现。这样可以保留约束并防止类型扩展:
input=['he and Chazz duel with all keys on the line.']
from ICE import CollocationExtractor
extractor = CollocationExtractor.with_collocation_pipeline('T1' , bing_key = 'Temp',pos_check = False)
print(extractor.get_collocations_of_length(input, length = 3))