REFACTOR: Better casting in JSONReviver.ts (#1780)

This commit is contained in:
David Walker 2024-11-19 11:45:26 -08:00 committed by GitHub
parent d824cd4fa6
commit 5faa418c74
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -95,16 +95,12 @@ export function Generic_fromJSON<T extends Record<string, any>>(
const obj = new ctor();
// If keys were provided, just load the provided keys (if they are in the data)
if (keys) {
/**
* The type of key is "keyof T", but the type of data is Record<string, unknown>. TypeScript won't allow us to use
* key as the index of data, so we need to typecast here.
*/
for (const key of keys as string[]) {
const val = data[key];
for (const key of keys) {
// This cast is safe (T has string keys), but still needed because "keyof T" cannot be used to index data.
const val = data[key as string];
if (val !== undefined) {
// This is an unsafe assignment. We may load data with wrong types at runtime.
// @ts-expect-error -- TypeScript won't allow this action: Type 'T' is generic and can only be indexed for reading.
obj[key] = val;
obj[key] = val as T[keyof T];
}
}
return obj;