Type alias Like<T, L>

Like<T, L>: T & {
    likeType?(like) => void;
}

Associates a type T with a loosely typed representation L. Loose type representations are modeled as a phantom method likeType?(like: L): void whose argument type is the loosely typed representation of T. Because the likeType method is optional, values of type T are assignable to type Like<T, L>, and vice versa.

The preferred way to associate loose type representations with a custom class is to declare a likeType?(like: L): void method on the class itself. The Like type is used to inject a phantom likeType method into an existing type. This enables ad hoc loose types to be declared without needing to change the declaration of the strict type.

Type Parameters

  • T

  • L

Type declaration

  • likeType?:function
    • Parameters

      Returns void

Example

Ad hoc number coercion

const NumberLike: FromLike<Like<number, string | boolean>> = {
fromLike(value: number | string | boolean): number {
return Number(value);
},
};

NumberLike.fromLike("42") // yields 42
NumberLike.fromLike(true) // yields 1

Example

Using an ad hoc conversion with a @Property fastener

class Person {
@Property({valueType: NumberLike})
readonly age!: Property<Like<number, string | boolean>>;
}

const person = new Person();
person.age.setValue("42");
person.age.value // yields 42

Generated using TypeDoc