Haxz Haxz - 8 months ago 31
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"
element instanceof Element
this works.

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


You're looking for the type guard is T:

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