Haxz Haxz - 3 months ago 15
TypeScript Question

Is there any way to type guards a block/function with my own validation function?

I'm trying to create a class to manage components, but I'm really stucked in a problem with a union type and the TypeScript type guards.

Screenshot of my code

I tried to validate a union type with my own type validation, but the TypeScript doesnt let me use variable as the valid type... When I validate with JavaScript default

typeof selectorOrElement === "string"
and
element instanceof Element
this works.

Is there any kind of notation or way to use my own type validation?

Answer

You're looking for the type guard is T:

function isString(value: any): value is string {
  return typeof value === 'string';
}
Comments