Skip to content

Latest commit

 

History

History
70 lines (50 loc) · 1.3 KB

never.md

File metadata and controls

70 lines (50 loc) · 1.3 KB

Partially disallow structural typing

type VariantA = {
  a: string
}

type VariantB = {
  b: number
}

declare function fn(arg: VariantA | VariantB): void

const input = {a: 'hello', b: 42}
fn(input) // Allowed, but this is not the usecase we want to cover.

Solution:

type VariantA = {
  a: string
  b?: never 
}

type VariantB = {
  a?: never
  b: number
}

declare function fn(arg: VariantA | VariantB): void

const input = {a: 'hello', b: 42}
fn(input) 

Argument of type '{ a: string; b: number; }' is not assignable to parameter of type 'VariantA | VariantB'.
  Type '{ a: string; b: number; }' is not assignable to type 'VariantB'.
    Types of property 'a' are incompatible.
      Type 'string' is not assignable to type 'undefined'.

Prevent unintended API Usage

type Read = {}
type Write = {}
declare const toWrite: Write

declare class MyCache<T, R> {
  put(val: T): boolean;
  get(): R
}

const cache = new MyCache<Write, Read>();
cache.put(toWrite)

To design a read-only cache:

declare class ReadOnlyCache<R> extends MyCache<never, R> {};

const cache = new ReadOnlyCache<Read>();
cache.put(toWrite) // Argument of type 'Write' is not assignable to parameter of type 'never'.

References