gpt4 book ai didi

typescript 如何从常量属性值推断类型

转载 作者:行者123 更新时间:2023-12-05 06:08:01 24 4
gpt4 key购买 nike

我想从先前定义的常量中获取属性的类型。

const my_constant = {
user: {
props: {
name: {
type: 'string'
}
}
},
media: {
props: {
id: {
type: 'number'
}
}
}
} as const;

type Name = keyof typeof my_constant;

type Constructed<T extends Name> = {
[K in keyof typeof my_constant[T]['props']]: typeof my_constant[T]['props'][K]['type']

// ~~~ Type '"type"' cannot be used to index type ...
}

我不明白为什么我不能使用“type”作为索引,但我可以使用“props”。

如果 typescript 可以推断出总有“props”属性,为什么它不能推断出总有“type”?

有没有其他方法可以获取类型?

我想要实现的是这样的:


const user:Constructed<'user'> = {
name: 'John'
}

const media:Constructed<'media'> = {
id: 123
}

const user2:Constructed<'user'> = {
name: 444
// ~~~ Error
}

const media2:Constructed<'media'> = {
id: 'something'
// ~~~ Error
}

这是带有确切错误的 playground 链接:

Playground Link

最佳答案

Typescript 不能使用字符串来索引常量。它需要正确的 key 。您可以检查对象是否具有 type 属性,也可以使用映射类型来获取真实类型,而不仅仅是“字符串”。

const my_constant = {
user: {
props: {
name: {
type: 'string'
}
}
},
media: {
props: {
id: {
type: 'number'
}
}
}
} as const;

type Name = keyof typeof my_constant;

type InferType<T> = T extends {type: infer I} ? I : never;

interface Mapped {
string: string;
number: number;
}

type Constructed<T extends Name> = {
[K in keyof typeof my_constant[T]['props']]:
InferType<typeof my_constant[T]['props'][K]> extends keyof Mapped ?
Mapped[InferType<typeof my_constant[T]['props'][K]>] : never
}

Playground Link

关于 typescript 如何从常量属性值推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65216730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com