-
Notifications
You must be signed in to change notification settings - Fork 640
Closed
Description
createFactory
seems to be quite impossible to make strongly typed in Typescript, without mapped types (even when not taking into consideration the partial subtypes of snapshots)
Two sample playgrounds demonstrating some of the problems:
factories are not functions, but expose (possibly null) create method (note the create!()
)
Something like: microsoft/TypeScript#13257 could definitely help!
This is the best I could do so far:
type Factory<T> = T & { create?(): T }
function createFactory<T>(base: T): Factory<T> {
return null as any
}
function primitive<T>(value: T): Factory<T> {
return null as any
}
const A = createFactory({
x: primitive(3 as number),
y: primitive("boe" as string)
})
// factory is invokable
const a = A.create!()
// property can be used as proper type
const z: number = a.x
// property can be assigned to crrectly
a.x = 7
// wrong type cannot be assigned
a.x = "stuff" // Red is ok
// sub factories work
const B = createFactory({
sub: A
})
const b = B.create!()
// sub fields have proper type
b.sub.x = 4
const d: string = b.sub.y
// sub fields can be reassigned
b.sub = A.create!()
Metadata
Metadata
Assignees
Labels
No labels