Right now the type checker for Typescript API doesn't expose methods for checking assignability and building types. See issue #9879 and #29432 on the Typescript github repository.
To fill in the gap while this issue is being discussed this library aims to provide the most essential helper functions for working with types in Typescript.
Furthermore, this library can help you construct types (called SimpleType) which can be serialized and easy analyzed.
This library has more than 35000 tests comparing results to actual Typescript diagnostics (see test-types.ts).
Installation
npm install ts-simple-type
How to use
The API is very simple. For example if you want to check if Typescript type typeB is assignable to typeA, you can use the following function.
To make it easier to work with typescript types this library works by (behind the curtain) converting them to the interface SimpleType. Most functions in this library work with both SimpleType and the known and loved Typescript-provided Type interface. This means that you can easily create a complex type yourself and compare it to a native Typescript type. It also means that you can use this library to serialize types and even compare them in the browser.
The SimpleType interface can be used to construct your own types for typechecking.
const typeA = checker.getTypeAtLocation(nodeA);const typeB = checker.getTypeAtLocation(nodeB);/* For this example, let's say: - typeA is number - typeB is string[]*/// typeToStringtypeToString(typeA)> "number"typeToString(typeB)> "string[]"// isAssignableToTypeisAssignableToType(typeA, typeB, checker)> falseisAssignableToType(typeA, { kind: "NUMBER" }, checker)> trueisAssignableToType(typeB, { kind: "ARRAY", type: {kind: "STRING"}}, checker)
API Documentation
For functions that take either a native Typescript Type or a SimpleType the TypeChecker is only required if a Typescript Type has been given to the function.
isAssignableToType
isAssignableToType(typeA: Type | SimpleType, typeB: Type | SimpleType, checker?: TypeChecker): boolean
Returns true if typeB is assignable to typeA.
isAssignableToPrimitiveType
isAssignableToPrimitiveType(type: Type | SimpleType, checker?: TypeChecker): boolean
Returns true if type is assignable to a primitive type like string, number, boolean, bigint, null or undefined.