简体   繁体   English

返回实例类型<t>或未定义</t>

[英]Return InstanceType<T> OR undefined

I'm creating a registry where if I pass in a class to a Map as a key, it will return an instance of that class as a value.我正在创建一个注册表,如果我将Map作为键传递给 Map,它将返回该 class 的一个实例作为值。

class Car {}
class HondaCar extends Car{}

type Newable = { new (...args: unknown[]): unknown };

export default class CarRegistry {
  private cars = new Map<NewableFunction, Car>();

  register(instance: Car) {
    this.cars.set(instance.constructor, instance);
  }

  get<T extends Newable>(type: T) {
    if (!this.cars.has(type)) return undefined;
    return this.cars.get(type) as InstanceType<T>;
  }
}

The expected functionality is something like:预期的功能类似于:

const registry = new CarRegistry()
registry.register(new HondaCar())
car = registry.cars.get(HondaCar)

The issue, however, is that I want register.cars.get to be able to return undefined .然而,问题是我希望register.cars.get能够返回undefined For some reason, no matter what combination of types I try for get , it's not possible in this context to return undefined .出于某种原因,无论我为get尝试什么样的类型组合,在这种情况下都不可能返回undefined Here's the signature TypeScript generates for me:这是 TypeScript 为我生成的签名:

(method) CarRegistry.get<typeof HondaCar>(type: typeof HondaCar): HondaCar

The types are completely correct, which is great, but I want this function to return HondaCar | undefined类型完全正确,这很好,但我希望这个 function 返回HondaCar | undefined HondaCar | undefined . HondaCar | undefined This is necessary because there is a large chance that the car has not yet been registered, and I want the caller to account for that.这是必要的,因为汽车很可能尚未注册,我希望呼叫者对此负责。

Is there any way I can return InstanceType<T> OR undefined ?有什么办法可以返回InstanceType<T> OR undefined吗?

This can happen if strictNullChecks are disabled.如果禁用strictNullChecks ,就会发生这种情况。 Enabling "strict": true in my TSConfig resolved my issue.在我的 TSConfig 中启用"strict": true解决了我的问题。

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

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