Imagine a scenario with a simple code snippet to illustrate the issue:
interface I {
n?: number;
s?: string;
}
const a: I = {
n: 1,
}
const b: I = {
n: 2,
s: 'b',
}
const props = ['n', 's'] as const;
for (const prop of props) {
if (!a[prop]) {
// encountering an error:
// TS2322: Type 'string | number' is not assignable to type 'never'.
// Type 'string' is not assignable to type 'never'.
a[prop] = b[prop];
}
}
If a
and b
are of the same type, accessing the same property prop
, shouldn't it work smoothly?
- If
b[prop]
holds a number, thena[prop]
should accept numbers - If
b[prop]
contains a string, thena[prop]
should accept strings - If
b[prop]
is undefined, it implies that the prop is optional?
So, what could be the missing piece here?
Update: After simplifying the example too much, the fix was to eliminate the as const
part... However, this behavior might be specific to my setup since I'm utilizing strict: true
in tsconfig.json
...
When attempting access without as const
, I encounter the TS7053 error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'I'.
No index signature with a parameter of type 'string' was found on type 'I'.
To resolve this, add the as const
or use
for(const prop of props as ('n' | 's')[]) {
Later on, when faced with the original error (easily resolved by adding as any
but aiming to avoid it)