Skip to content

Instantly share code, notes, and snippets.

@mlhaufe mlhaufe/factory-test.ts
Last active Jan 30, 2018

Embed
What would you like to do?
TypeScript Factory type
type Factory<T extends { kind: string }> = {
// Can we do better than (...args: any[]) ?
readonly [P in T['kind']]: (...args: any[]) => T
}
type Bool = { kind: 'False' } | { kind: 'True' }
let BoolFactory: Factory<Bool> = {
False() { return { kind: 'False' } },
True() { return { kind: 'True' } }
}
type Shape = { kind: 'Rect', width: number, height: number }
| { kind: 'Square', size: number }
| { kind: 'Circle', radius: number }
let shapeFactory: Factory<Shape> = {
Rect(width: number, height: number) { return {kind: 'Rect', width, height} },
Square(size: number) { return {kind: 'Square', size } },
Circle(radius: number){ return {kind: 'Circle', radius } }
}
// Type checking too generic here
let circle = shapeFactory.Circle(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.