Interface FromLike<T>

Conversion from loosely typed values to a strictly typed instances.

Example

Generic wrapper class

Consider the case of implementing a generic wrapper class. Although the wrapper encapsulates a particular concrete type, the API for the wrapper should accept similarly typed values--but not any value. Two generic types are in play here, the strict type being wrapped, and a loose type that's accepted as arguments and internally converted to the strict type. These types are not independent of each other; each strict type has an associated loose type from which it can be converted. To minimize boilerplate, the wrapper class should only need to be parameterized with a single type.

These requirements can be cleanly met with a combination of [[Like]] types and FromLike conversions. The generic wrapper class described above can be implemented as follows:

class GenericWrapper<T> {
valueType: FromLike<T>;
value: T;
constructor(valueType: FromLike<T>, value: T) {
this.valueType = valueType;
this.value = value;
}
set(value: T | LikeType<T>): void {
this.value = this.valueType.fromLike(value);
}
}

When no loose type conversions are needed, GenericWrapper can be instantiated with an identity FromLike converter.

const greeting = new GenericWrapper(FromLike<string>(), "");
greeting.set("Hello, world!");
greeting.value // yields "Hello, world!";

A GenericWrapper parameterized with a Like type and accompanying FromLike conversion can be set with any like-typed value.

const NumberLike: FromLike<Like<number, string | boolean>> = {
fromLike(value: number | string | boolean): number {
return Number(value);
},
};
export const foo = new GenericWrapper(NumberLike, 0);
foo.set("42")
foo.value // yields 42

Type Parameters

  • T

Hierarchy

  • FromLike

Methods

Methods

  • Coerces a loosely typed value to a strictly typed instance.

    Parameters

    Returns T

Generated using TypeDoc