【发布时间】:2021-04-27 20:33:50
【问题描述】:
我在 TypeScript 中有一个简单的案例,其中我有一个带有泛型类型 T 的接口,它扩展了一个枚举 E。根据类型分配配置类型。
enum E { "A", "B" }
type ConfigsBase = { [K in E]: object }
interface Configs extends ConfigsBase {
[E.A]: { a: string };
[E.B]: { b: number };
}
interface MyInterface<T extends E> {
type: T;
config: Configs[T];
}
问题是我如何以从对象隐式推断出泛型类型的方式使用此接口。这样当配置错误时我会得到有用的类型错误。
const a: ??? = {
type: E.A,
config: { a: 1 },
}
// => I want this to give a typescript error because 1 is not a string
我需要为??? 插入什么,以便打字稿给出配置错误的错误。它应该类似于const a: MyInterface<look for yourself what T is>。
我通过使用自动推断类型的标识函数找到了一个相对繁琐的解决方案:
const inferType = <T extends E>(obj: MyInterface<T>): MyInterface<T> => obj
const a = inferType({
type: E.A,
config: { a: 1 },
})
// => TypeScript error: Type 'number' is not assignable to type 'string'
是否可以在不使用函数的情况下通过类型注释更优雅地做到这一点?
【问题讨论】:
-
这是一个玩场景的游乐场:typescriptlang.org/play?#code/…。
-
你能接受我的问题吗?我会很高兴的。
标签: typescript typescript-generics