Skip to content

Latest commit

 

History

History
96 lines (86 loc) · 3.25 KB

extension.md

File metadata and controls

96 lines (86 loc) · 3.25 KB

Extension

An extension is the code that implements a protocol.

For example:

// Value is a protocol
export interface Value<T> {
    /**
     * `implementsValue()` helps the caller detect that we
     * implement the protocol `Value`
     */
    implementsValue(): this is Value<T>;

    /**
     * `valueOf()` returns the data stored in this value.
     */
    valueOf(): T;
}

export class MediaType {
    public implementsValue(): this is Value<string> {
        return true;
    }

    public valueOf(): string {
        return this.value;
    }
}

In the example above, the extension is made up of the methods MediaType.implementsValue() and MediaType.valueOf().

We've adoped the term extension from the Swift community. We do our best to think about extensions in the same way too.

In particular, we encourage writing extensions as standalone code that is patched into values at runtime using @safelytyped/ts-protocol-extensions.