From 5faa418c74482ddc95b5a52b5578843553a0eb70 Mon Sep 17 00:00:00 2001 From: David Walker Date: Tue, 19 Nov 2024 11:45:26 -0800 Subject: [PATCH] REFACTOR: Better casting in JSONReviver.ts (#1780) --- src/utils/JSONReviver.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/utils/JSONReviver.ts b/src/utils/JSONReviver.ts index f278131af..c1736259b 100644 --- a/src/utils/JSONReviver.ts +++ b/src/utils/JSONReviver.ts @@ -95,16 +95,12 @@ export function Generic_fromJSON>( 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. 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;