Skip to content

Proposal: Run-time Type Checks #7607

@srijs

Description

@srijs

Hi there!

I am writing a lot of code in an environment where JavaScript and TypeScript freely interact with each other. One thing that we continue to run into is where we would write a function in TypeScript, say:

export function add(x: number, y: number): number {
  return x + y;
}

This function is callable from JavaScript, where we're allowed to do things like:

add('abc', undefined)

This has lead us to introduce type checks for all exported functions in TypeScript, although they really feel verbose in a typed language.

export function add(x: number, y: number): number {
  if (typeof x !== 'number' || typeof y !== 'number') {
    throw new TypeError('x and y need to be numbers');
  }
  return x + y;
}

My idea is to provide an optional flag, say --insertRuntimeTypeChecks, that makes the compiler insert these kinds of checks for function arguments.

The feature will probably be a bit more complicated when thinking about structural types, etc., especially in interplay with classes (it is my understanding that classes are type-checked structurally, not nominally, is that correct?).

But even having it only for primitive types (checking for object, string, number, etc.) could provide a lot of benefits for those of us who write code that interacts with JavaScript, especially should #7140 land, to spare us from manually writing if (x === null) ....

I'd be interested in giving implementing this a shot, if there's interest from the maintainers.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions