I have a generic function that fetches some data:
function getData<T extends A | B | C>(initial: T[]): T[] {
const [data, setData] = useState<T[]>([]);
useEffect(() => {
...some query
setData(query result);
}, []);
return data;
}
interface A {
someKeyA: string;
}
interface B {
someKeyB: number;
}
interface C {
someKeyC: A;
}
In another helper function for query i need to get key types of T. If initial data array is not empty i can do this and it works
const _key = typeof data[0].["someKeyA" as keyof T];
But sometimes initial data array is empty and then this fails because data[0] is undefined.
What i would need is to get K extends keyof T if there is no passed in data.
Is it possible to get typeof key from generic interface by key value or maybe create some temporary object with type T?
question from:
https://stackoverflow.com/questions/65917619/how-to-get-interface-key-type-in-generic-function 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…