如何解决"Type circularly references itself error"?
How to resolve "Type circularly references itself error"?
以下是具有预期结果的问题示例:
const actionTypes = {
name: {
set: "name/set",
},
} as const;
type ActionTypes = { [key: string]: (string | ActionTypes) }; //record value is string or ActionTypes
// "GetActionType" circularly references itself
type GetActionType<A extends ActionTypes> = A extends Record<
string,
infer Value
>
? Value extends string
? Value
: GetActionType<Value> // "GetActionType" is not generic
: unknown;
type SiteAction = GetActionType<typeof actionTypes>; // "GetActionType" is not generic
// expected to be 'name/set'
有没有办法在不 运行 出错的情况下完成此操作?
编辑
将 as const
添加到 actionTypes 的声明中,并在下面正确引用常量
TypeScript 版本 4.0.2
游乐场link.
以下应该有效:
与您的方法有两个主要区别:
- 翻转
Value extends string
到 Value extends ActionTypes
递归
- 标记为
siteActionTypes
到 as const
以推断特定类型
const siteActionTypes = {
name: {
set: 'name/set'
}
} as const
type ActionTypes = { [key: string]: string | ActionTypes }
type GetActionType<A extends ActionTypes> = A extends Record<string, infer Value>
? Value extends ActionTypes
? GetActionType<Value>
: Value
: unknown
type SiteAction = GetActionType<typeof siteActionTypes>
// SiteAction has type 'name/set'
以下是具有预期结果的问题示例:
const actionTypes = {
name: {
set: "name/set",
},
} as const;
type ActionTypes = { [key: string]: (string | ActionTypes) }; //record value is string or ActionTypes
// "GetActionType" circularly references itself
type GetActionType<A extends ActionTypes> = A extends Record<
string,
infer Value
>
? Value extends string
? Value
: GetActionType<Value> // "GetActionType" is not generic
: unknown;
type SiteAction = GetActionType<typeof actionTypes>; // "GetActionType" is not generic
// expected to be 'name/set'
有没有办法在不 运行 出错的情况下完成此操作?
编辑
将 as const
添加到 actionTypes 的声明中,并在下面正确引用常量
TypeScript 版本 4.0.2
游乐场link.
以下应该有效:
与您的方法有两个主要区别:
- 翻转
Value extends string
到Value extends ActionTypes
递归 - 标记为
siteActionTypes
到as const
以推断特定类型
const siteActionTypes = {
name: {
set: 'name/set'
}
} as const
type ActionTypes = { [key: string]: string | ActionTypes }
type GetActionType<A extends ActionTypes> = A extends Record<string, infer Value>
? Value extends ActionTypes
? GetActionType<Value>
: Value
: unknown
type SiteAction = GetActionType<typeof siteActionTypes>
// SiteAction has type 'name/set'