Haxz Haxz - 1 year ago 69
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?

Answer Source

You're looking for the type guard is T:

function isString(value: any): value is string {
  return typeof value === 'string';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download