javascript 检查null或undefined时,Typescript异常类型推断{}

af7jpaap  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(78)

在我们从typescript 4.9.3升级到5.0.2之后,我们在Assert类型时遇到了以下错误。
有谁知道为什么函数“wontWorking”不起作用?我希望这个函数推断vRecord<string, any>以及,但相反,它推断它为{},也调用assertRecord后,它仍然保持{}的类型。.

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});

我们期望wontWorking函数在调用assertRecord作为Record<string,any>之后也会推断v的类型。
TSPlayground链接

bhmjp9jg

bhmjp9jg1#

这被认为是错误/回归。
参见本期。

相关问题