[英]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.