让我们假设我有这两种类型:
type Foo = {
foo: string
}
type Bar = {
bar: number
}
有没有一种方法可以在不创建包装器类型的情况下键入对象文字的各个字段(如果存在的话,我正在寻找正确的语法)?
This is what I want to avoid:个
type Wrapper = {
a: Foo
b: Bar
}
const x: Wrapper = {
a: { foo: 'foo' },
b: { bar: 123 }
}
This is what I'm trying to do:个
const x = {
// x.a should be of type Foo, enforced by the compiler
a: { foo: 'foo' },
// x.b should be of type Bar, enforced by the compiler
b: { bar: 123 }
}
What I considered, but is not suitable:个
- 使用
Record
类型没有任何意义,因为我丢失了各个字段及其各个类型:
const x: Record<string, Foo | Bar> = {
a: { foo: 'foo' },
b: { bar: 123 }
}
- 类型转换(或在TS中叫它什么)也不合适,因为现在我放松了编译器判断和内容辅助.至少在这个版本中,
x
的类型是正确的:
const x = {
a: { foo: 'foo' } as Foo,
b: { bar: 123 } as Bar
}