如何推断深层对象?
How to infer deep object?
假设我有一个看起来像这样的对象
const myObj = {
homePage: ["on", {
title: 'Home Page',
}]
})
我想限制对象值但推断键。我看到另一个 SO 解决了我的问题(部分)
export type OnOffFormat = "off" | "on";
export type AcceptedValue = string | number | boolean;
export type ArrayFormat = [OnOffFormat] | [OnOffFormat, Record<string, AcceptedValue>]
export type RuleFormat = OnOffFormat | ArrayFormat
const asParsedConfig = <T, Z>(config: { [K in keyof T]: OnOffFormat | [OnOffFormat, {
[TK in keyof Z]: AcceptedValue;
} ]}) => config;
export const myObj = asParsedConfig({
homePage: ["on", {
title: 'Home page',
}]
})
问题是,当我尝试检查时 myObj.homePage[1]
TypeScript 无法识别其键和值
如您所见,second
被推断为 {}
而不是 { title: "Home Page" }
你知道我该怎么做才能推断出它的配置吗?
谢谢!
您需要以不同的方式构建泛型。从最里面最简单的类型(AcceptedValue
)开始,然后逐层往上。这将起作用:
type OnOffFormat = "off" | "on";
type AcceptedValue = string | number | boolean;
const asParsedConfig = <
Value extends AcceptedValue,
R extends Record<string, Value>,
Config extends Record<string, OnOffFormat | [OnOffFormat, R]>,
>(config: Config) => config;
const myObj = asParsedConfig({
homePage: ["on", {
title: 'Home page',
}]
});
const second = myObj.homePage[1];
变量 second
将具有您想要的类型。
假设我有一个看起来像这样的对象
const myObj = {
homePage: ["on", {
title: 'Home Page',
}]
})
我想限制对象值但推断键。我看到另一个 SO 解决了我的问题(部分)
export type OnOffFormat = "off" | "on";
export type AcceptedValue = string | number | boolean;
export type ArrayFormat = [OnOffFormat] | [OnOffFormat, Record<string, AcceptedValue>]
export type RuleFormat = OnOffFormat | ArrayFormat
const asParsedConfig = <T, Z>(config: { [K in keyof T]: OnOffFormat | [OnOffFormat, {
[TK in keyof Z]: AcceptedValue;
} ]}) => config;
export const myObj = asParsedConfig({
homePage: ["on", {
title: 'Home page',
}]
})
问题是,当我尝试检查时 myObj.homePage[1]
TypeScript 无法识别其键和值
如您所见,second
被推断为 {}
而不是 { title: "Home Page" }
你知道我该怎么做才能推断出它的配置吗? 谢谢!
您需要以不同的方式构建泛型。从最里面最简单的类型(AcceptedValue
)开始,然后逐层往上。这将起作用:
type OnOffFormat = "off" | "on";
type AcceptedValue = string | number | boolean;
const asParsedConfig = <
Value extends AcceptedValue,
R extends Record<string, Value>,
Config extends Record<string, OnOffFormat | [OnOffFormat, R]>,
>(config: Config) => config;
const myObj = asParsedConfig({
homePage: ["on", {
title: 'Home page',
}]
});
const second = myObj.homePage[1];
变量 second
将具有您想要的类型。