Function to test variable type or throw in TypeScript?

typescript check type
typescript dictionary type
typescript object key type
typescript map type
typescript conditional types
typescript function type
typescript null check operator
typescript keyof

I want to have a function to test if a class variable is not null and use it in follow up function calls. But got TS complaints. Encapsulate this validate function because I need to call it in many of my methods.

class A {
  point: Point | null
  validatePoint() {
    if (!this.point) throw new Error()
  }

  update(p: Point | null) {
    this.validatePoint()
    // ts complains this.point can be null
    doSomething(this.point)
  }
}

One option is to use a type guard instead, and throw in update instead of validatePoint:

class A {
    point: Point | null;
    validatePoint(p: Point | null): p is Point {
        return Boolean(this.point);
    }
    update(p: Point | null) {
        if (!this.validatePoint(this.point)) {
            throw new Error();
        }
        doSomething(this.point);
    }
}

But using a separate method for something like this seems a bit overkill:

update(p: Point | null) {
    if (this.point === null) {
        throw new Error();
    }
    doSomething(this.point);
}

If you have to put it in a separate function, then another option is for validatePoint to return the validated point (since this sort of thing can't be used to narrow the type of a parent object IIRC):

class A {
    point: Point | null;
    validatePoint() {
        if (this.point === null) {
            throw new Error();
        }
        return this.point;
    }
    update(p: Point | null) {
        const validatedPoint = this.validatePoint();
        doSomething(validatedPoint);
    }
}

TypeScript 2.0 � TypeScript, The effects on subject variable types accurately reflect JavaScript semantics (e.g. Entity) { // Throw exception if e is null or invalid entity } function processEntity(e ?: function test(x: string | null) { if (x === null) { return; } x; // type of x is string in� The scope of a variable determines which part of the program can access it. We can define a variable in three ways, so as to limit their visibility. One is the local variable or block variable, which has the scope of a code block (block scope or local scope). The second one is a function variable or class variable which has the function/class

Typescript 3.7 introduces assertions in control flow analysis:

class A {
    point: Point | null = null;
    validatePoint(): asserts this is { point: Point} {
        if (!this.point) throw new Error()
    }

    update(p: Point | null) {
        this.validatePoint()
        // now ts is sure that this.point can't be null
        doSomething(this.point)
    }
}

Playground

Advanced Types � TypeScript, We can't be sure whether a variable typed as Bird | Fish has a fly method. A type guard is some expression that performs a runtime check that guarantees the padding + value; } throw new Error(`Expected string or number, got '${padding}' . Type Assertion in TypeScript Here, you will learn about how TypeScript infers and checks the type of a variable using some internal logic mechanism called Type Assertion. Type assertion allows you to set the type of a value and tell the compiler not to infer it.

You should be explicitly checking for null using an if(this.point === null) statement. Although I don't think you need a separate method for this, it seems a bit overkill.

TypeScript 3.7 � TypeScript, For more details, check out their pull request and the nullish coalescing proposal There's a specific set of functions that throw an error if something unexpected instead tells TypeScript that a specific variable or property has a different type. TypeScript is a typed language that allows you to specify the type of variables, function parameters, returned values, and object properties. Here an advanced TypeScript Types cheat sheet with examples. Let's dive in Intersection Types Union Types…

In update, you validate if this.point is null.

If this.point is null, an error is thrown and doSomething is not invoked. If this.point is not null, that means this.point is Point type.

So it is not possible that this.point is null, when doSomething is invoked. That's why TS complains like that.

Making exceptions type safe in Typescript, If your function needs to throw a new type of error, you can simply do add As per Typescript rules, you'll have to check isError field to read the� Type checking. Our problem is classic in Typescript: an object type is undifferentiated, and we would like to differentiate the different cases.

Exception Handling - TypeScript Deep Dive, JavaScript has an Error class that you can use for exceptions. You throw an The next developer cannot know which function might throw the error. The person� tl;dr. When checking for primitive types in TypeScript , typeof variable === “string” or typeof variable === “number” should do the job.. When checking for HTMLElement or HTMLDivElement type of objects, variable instanceof HTMLElement or variable instanceof HTMLDivElement type of check should be the right one.

Conditional types in TypeScript, Let's add basic types to this function so we can let TypeScript worry about Here we've introduced a type variable T for the text parameter. declare const a: A const b: B = a // type check succeeds only if A is assignable to B and that TypeScript had just thrown its hands up in the air and said, "Sorry mate,� TypeScript can figure the return type out by looking at the return statements, so we can also optionally leave this off in many cases. Writing the function type # Now that we’ve typed the function, let’s write the full type of the function out by looking at each piece of the function type.

Suggestion: `throws` clause and typed catch clause � Issue #13219 , The typescript type system is helpful in most cases, but it can't be utilized when handling exceptions. For example: function fn(num: number): void { if (num === 0) { throw You can test here the result tips: hover typedError at line 106 Allow ` unknown` type annotation on catch clause variable #36775. TypeScript - Variable . TypeScript follows the same rules as JavaScript for variable declarations. Variables can be declared using: var, let, and const. var. Variables in TypeScript can be declared using var keyword, same as in JavaScript. The scoping rules remains the same as in JavaScript. let

Comments
  • I'm looking for an TS instruction to let it know point can not be null. I have many functions call validatePoint, otherwise I won't need to encapsulate it into a function.
  • Thanks! upvote for a valid approach, still looking for a direction if is this in the road map of TS feature list.
  • This is awesome! I tried it in playground it it works perfectly, but somehow in my local I got cannot find name asserts. My ts version is 3.7.2.
  • The error comes from typescript compiler or somewhere else? (e.g. ide, eslint)
  • it is from ide.
  • I also tried to run it in jest, and got Unexpected token, expected "{" regarding this function
  • Thanks! I ended up with a different implementation. Upvote for a valid approach.
  • I have many methods needs to validatePoint. That's why I want to make it a function.
  • what you said is right in run time. it is not possible that this.point is null, when doSomething is invoked. But TS complains because it thinks this.point can be null. That why I want to tell ts compiler is can not be null.
  • Yeah, but again I need to have it in all my caller functions which kind of violate my encapsulate in one function idea.