我为此挣扎了一段时间。我的问题如下:我知道数据结构。
const array = [
{
foo: "foo1" as const,
bar: "any string"
baz: 2
},
{
foo: "foo2" as const,
bar: "any string 2"
baz: 2
}
]
我可以简单地推断类型只有foo
变量自动完成并具有精确值吗?
array[0].foo // has possible values of "foo1", "foo2"
但是
array[0].bar // has any string as a value
array[0].baz // has any number as a value
假设我有一些已知类型的接口:
interface Example {
name: ???? // how should i type it?
bar: string,
baz: number,
}
我试图在不为所有可能的名称声明类型的情况下对其进行存档。如果有任何建议,我将不胜感激。
编辑:
我尝试参数化示例界面:
interface Example<Name> { name: Name, ... rest of types }
type MapToNamed<T> = T extends { name: infer Name } ? Example <Name> : never
type TargetType = MapToNamed<typeof array[number]>;
但这迫使我使用as any as MapToNamed<typeof array>
,我不确定这是否正确。
"foo1" as const
称为const
断言,用于只读值
对于您的情况,它不会影响您的类型声明
你可以像下面的一样定义Example
interface Example {
foo: string, //apply for all string types
bar: string,
baz: number,
}
const array: Example[] = [
{
foo: "foo1" as const, //consider as a read-only string
bar: "any string",
baz: 2
},
{
foo: "foo2" as const, //consider as a read-only string
bar: "any string 2",
baz: 2
}
]
console.log({ array })
游乐场
如果您想要固定类型,如foo1
和foo2
。您可以使用枚举类型
enum Foo {
"foo1",
"foo2"
}
interface Example {
foo: keyof typeof Foo, //"foo1" | "foo2"
bar: string,
baz: number,
}
const array: Example[] = [
{
foo: "foo1" as const,
bar: "any string",
baz: 2
},
{
foo: "foo2" as const,
bar: "any string 2",
baz: 2
}
]
console.log({ array })
游乐场