如何在TypeScript中编写一个函数,该函数可以查询深层对象并在调用时返回嵌套键的类型



我有以下预定义的对象:

export const catalog = {
category1: {
newDomain: 'Hello'
},
category2: {
otherStuff: 30
}
};

现在我需要实现两件事:

  • 获取嵌套键的并集,即newDomainotherStuff的并集
  • 一个接受两个参数的函数-第一个是有效的类别id(catalog对象中的顶级键(,第二个参数是所选类别id下的有效键,最后返回所选键的值

这意味着我需要一个函数validate,这样:

const value1: string = validate('category1', 'newDomain');
const value2: number = validate('category2', 'otherStuff');

验证函数的任何其他组合都应该失败。

编辑:我忘记回答第一部分(获得嵌套键的并集(:

TS游乐场

type Values<T> = T[keyof T];
type NestedKey<T extends Record<PropertyKey, Record<PropertyKey, unknown>>> =
Values<T> extends infer T1 ? (T1 extends T1 ? keyof T1 : never) : never;
const catalog = {
category1: { newDomain: 'Hello' },
category2: { otherStuff: 30 },
};
type NestedCatalogKey = NestedKey<typeof catalog>; // "newDomain" | "otherStuff"

首先,编写一个函数来为任何具有对象值的对象执行此操作,然后编写:

TS游乐场

function validate <
R,
K0 extends PropertyKey,
K1 extends PropertyKey,
T extends Record<K0, Record<K1, R>>,
>(l0Key: K0, l1Key: K1, obj: T): R {
return obj[l0Key][l1Key];
}
const catalog = {
category1: { newDomain: 'Hello' },
category2: { otherStuff: 30 },
};
function validateCatalog <
K0 extends keyof typeof catalog,
K1 extends keyof typeof catalog[K0],
>(l0Key: K0, l1Key: K1): typeof catalog[K0][K1] {
return validate(l0Key, l1Key, catalog);
}
const value1 = validateCatalog('category1', 'newDomain'); // string
const value2 = validateCatalog('category2', 'otherStuff'); // number
const value3 = validateCatalog('category1', 'otherStuff'); /*
~~~~~~~~~~~~
Argument of type '"otherStuff"' is not assignable to parameter of type '"newDomain"'.(2345) */
const value4 = validateCatalog('category2', 'newDomain'); /*
~~~~~~~~~~~
Argument of type '"newDomain"' is not assignable to parameter of type '"otherStuff"'.(2345) */
console.log({ value1, value2 }); // { value1: "Hello", value2: 30 }

最新更新