interface A {
name?: string
age: number
}
var a: A = {
name: '',
age: 23
}
var result:A = (Object.keys(a) as Array<keyof A>).reduce((prev, key) => {
if (a[key] || a[key] === 0) {
prev[key] = a[key] // an error was reported regarding `Type 'undefined' is not assignable to type 'never'`
}
return prev
}, {} as A)
console.log(JSON.stringify(result))
This code snippet above is a reproduction of the issue.
It was observed that the code works with typescript@~3.4.0, however, it does not compile with typescript@^3.5.0. Reviewing the changelog between versions 3.4 and 3.5 did not provide any clues on this difference.
Hypothesizing that the problem might be due to the absence of an index signature
, the following adjustment was made:
interface A {
name?: string
age: number
[K:string]:any <-- added this line
}
var a: A = {
name: '',
age: 23
}
var result:A = (Object.keys(a) as Array<keyof A>).reduce((prev, key/* validation lost */) => {
if (a[key] || a[key] === 0) {
prev[key] = a[key]
}
return prev
}, {} as A)
console.log(JSON.stringify(result))
The previous error no longer occurs, but the type of key
within the reduce
callback function now becomes string|number
, resulting in the loss of type validation for the key.
Is this the expected behavior?
If so, how can we resolve the issue of
Type 'undefined' is not assignable to type 'never'
while maintaining type checking for the key
variable?