假設我有一個看起來像這樣的物件
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" }
你知道我可以如何推斷它的配置嗎?謝謝 !
uj5u.com熱心網友回復:
您需要以不同的方式構建泛型。從最里面最簡單的型別(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將具有您想要的型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481449.html
上一篇:物件可能未定義
下一篇:型別聯合物件或物件陣列上沒有屬性
