JSPM

  • Created
  • Published
  • Downloads 80210
  • Score
    100M100P100Q145971F
  • License MIT

Relationship type checker functions for Typescript.

Package Exports

  • ts-simple-type

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (ts-simple-type) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

ts-simple-type

What is this?

Right now the type checker for Typescript API doesn't expose methods like isAssignableTo. See issue #9879 on the Typescript github repository which has been open for 2.5 years.

To fill in the gap while this issue is being discussed and resolved this library aims to provide the most essential helper functions for working with types in Typescript.

This library has more than 300 tests comparing results to actual Typescript diagnostics.

How to use

To make it easier to work with types this library converts them to the interface SimpleType. Most functions in this library work with both SimpleType and the known and loved Typescript-provided Type interface.

The API is very simple. For example if you want to see if "typeB" is assignable to "typeA", you can use the following function.

import { isAssignableToType } from "ts-simple-type";

const isAssignable = isAssignableToType(typeA, typeB, typeChecker);

API Documentation

Check assignability

isAssignableToType(typeA: Type | SimpleType, typeB: Type | SimpleType, checker: TypeChecker): boolean

Returns if typeB is assignable to typeA.

isAssignableToPrimitiveType(type: Type | SimpleType, checker: TypeChecker): boolean;

isAssignableToSimpleTypeKind(type: Type | SimpleType, kind: SimpleTypeKind | SimpleTypeKind[], options: IAssignableToSimpleTypeKindOptions): boolean;

isAssignableToType(typeA: Type | SimpleType, typeB: Type | SimpleType, checker: TypeChecker): boolean;

isAssignableToValue(type: SimpleType | Type, value: any, checker: TypeChecker): boolean;

simpleTypeToString(type: SimpleType): string;

toSimpleType(type: Type, options: IToSimpleTypeOptions): SimpleType;

SimpleType

The SimpleType interface can also be used to construct your own types for typechecking.

import { SimpleType, SimpleTypeKind } from "ts-simple-type";

const colors: SimpleType = {
    kind: SimpleTypeKind.UNION,
    types: [
        { kind: SimpleTypeKind.STRING_LITERAL, value: "RED" },
        { kind: SimpleTypeKind.STRING_LITERAL, value: "GREEN" },
        { kind: SimpleTypeKind.STRING_LITERAL, value: "BLUE" }
    ]
}

simpleTypeToString(colors)
> "RED" | "GREEN" | "BLUE"

isAssignableToType(colors, { kind: SimpleTypeKind.STRING_LITERAL, value: "YELLOW" })
> false

isAssignableToValue(colors, "BLUE")
> true

isAssignableToValue(colors, "PINK")
> false