[英]Typescript generic function to iterate over type keys
Typescript 的新手...是否可以在 typescript 中编写一个通用的 function 来打印给定类型的键? 就像是:
const getKeys = <T>(): string[] => { ??? }
interface A {
a: string,
b: number
}
getKeys<A>(); // returns ["a", "b"]
基本原理:我想写一个 function 它将得到一个原始的 object 和一个类型,并将检查它是否包含该类型的所有键。 我不想传递每种类型的密钥!
const checkKeys = <T>(rawData: any): boolean => { ??? }
interface A {
a: string,
b: number
}
const wrong = {
x: "aaa",
y: "bbb",
};
checkKeys<A>(wrong); // return false
我可以这样写:
const checkKeys = <T, K = keyof T>(data: any, ...keys: K[]) => {
for (const key of keys) {
if (!data[key]) {
return false;
}
}
return true;
}
interface A {
a: string,
b: number,
}
const right = { a: "a", b: "b" };
const wrong = { c: "a", b: "b" };
checkKeys<A>(right, "a", "b")); // returns true
checkKeys<A>(wrong, "a", "b")); // returns false
但是我总是必须为我想调用它的每种类型传递密钥,真的很烦人!
我知道 Typescript 只是类型系统,我们在运行时需要一些东西,但是有没有办法让 Typescript 在编译时生成keys
的值,因为它在我的情况下知道它们,甚至可以检查我是否只传递了可接受的keys
参数的值? 如果它在编译时那么聪明,它可以在编译为 Javascript 时为我生成一个数组。有没有我不知道的方法?
Typescript 不会为您生成代码。
您可能拥有的最接近的事情是提前创建可能的密钥:
const keys = ['a', 'b', 'c'] as const;
type Keys = typeof keys[number] // 'a' | 'b' | 'c'
type Foo = Record<Keys, string>;
const foo: Foo = {
a: 'foo',
b: 'bar',
c: 'baz',
}
这里的keys
是一个可以迭代的数组。
const sample = { a: '123', b: 123 } type Dict = { [key: string | number]: any} type CheckKeys<T extends Dict, S extends Dict> = keyof T extends never ? false : (keyof S extends keyof T ? true : false) function checkKeys< T extends Dict, S extends Dict, >(data: T, smp: S): CheckKeys<T, S> { const smpKeys = Object.keys(smp) for (const key in data) { if (!(key in smpKeys)) return false as CheckKeys<T, S> } return true as CheckKeys<T, S> } const right = { a: "a", b: "b" }; const wrong = { c: "a", b: "b" }; // const checkRight: true const checkRight = checkKeys(right, sample); // const checkWrong: false const checkWrong = checkKeys(wrong, sample);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.