javascript - Tipado extraño en Typescript {} al comprobar null o undefined
Después de actualizar de TypeScript 4.9.3 a 5.0.2 nos encontramos con el siguiente error al afirmar tipos.
¿Alguien sabe por qué la función "wontWorking" no funciona? Esperaría que esta función inferiera v como Record<string, any> también, pero en su lugar lo infiere como {} y además, después de llamar a assertRecord, todavía mantiene {} como tipo..
function assertRecord(v: unknown): asserts v is Record<string, any> {
if(typeof v !== 'object' || v === null) throw new Error ();
}
function wontWorking (v: unknown) : null | any{
// v = unkown
if ( v === null || v === undefined ) return null; //checking
// v = {}
assertRecord(v)
// v = {}
var s = v.fileName // ERROR: Property 'fileName' does not exist on type '{}'.
return s
}
wontWorking({fileName: 1231321});
function working (v: unknown) : null | any{
// v = unkown
// not checking
// v = unknown
assertRecord(v)
// v = Record<string, any>
var s = v.fileName
return s
}
working({fileName: 1231321});
function isNil ( v: unknown) : v is null | undefined{
return v === null || v === undefined
}
function workingWithCheck (v: unknown) : null | any{
// v = unkown
if ( isNil(v) ) return null; //checking
// v = unknown
assertRecord(v)
// v = Record<string, any>
var s = v.fileName
return s
}
workingWithCheck({fileName: 1231321});
Esperamos que la función wontWorking infiera el tipo de v después de llamar a assertRecord como Record<string,any> también.
Enlace de TS Playground
Respuesta #1
Se reconoció como error/regresión.
Vea este problema.