简体   繁体   English

TypeScript 回调类型

[英]TypeScript callback type

I have a case like this:我有一个这样的案例:

function createCar(name: string, callback: () => void)

function buildEngine(name: string): Engine

function createCarWithEngine(carName: string, engineName: string, callback: (param: Engine) => void) {
  let createdEngine = createdEngines.find((engine) => engine.name === engineName)
  if (!createdEngine) createdEngine = buildEngine(engineName)

  createCar(carName, () => callback(createdEngine)) // error here
}

VSCode tells me createdEngine maybe undefined. VSCode 告诉我createdEngine可能未定义。 However this is fine:不过这很好:

  const fn = callback(createdEngine)

  createCar(carname, () => fn)

Is this an intended behaviour?这是预期的行为吗?

The 2 cases aren't equivalent.两种情况不等价。

In the second case you call callback inside the function, in the first you defer the call for a later time.在第二种情况下,您在函数内部调用callback ,在第一种情况下,您将调用推迟到以后。

This will fail with the same error这将失败并出现相同的错误

 const fn = () => callback(createdEngine)

 createCar(carname, fn)

This is related to the fact that TS cannot know what happens with createdEngine because the function will be called later on.这与 TS 无法知道createdEngine发生了什么有关,因为稍后会调用该函数。 When you call createEngine inside your function then it knows that the calls are done in sync so it narrows the type down.当您在函数中调用createEngine时,它​​知道调用是同步完成的,因此它会缩小类型。

Interesting enough if you ensure that the type of createdEngine is Engine at all times then this will work.有趣的是,如果您确保createdEngine的类型始终是Engine ,那么这将起作用。

function createCarWithEngine(carName: string, engineName: string, callback: (param: Engine) => void) {
  let createdEngine = createdEngines.find((engine) => engine.name === engineName) || buildEngine(engineName)

  createCar(carName, () => callback(createdEngine)) // error here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM