The following demo shows an issue with TypeScript's type inference (tested with typescript@3.3.3333 and typescript@3.4.0-dev.20190226).
I do not know whether this should really be considered a bug but at least the same is working fine with Flow.
Pardon me, in case this has already been issued somewhere else in the past.
The following is working properly with Flow => types of store and self are properly inferred as { count: number, increment(): void }.
Check here to see that the Flow code is fine.
// @flow
function createStore<T>(init: (self: T) => T): T {
const ret: T = (({}: any): T)
// assume some change detector logic here
// (skipped to keep demo simple)
Object.assign(ret, init(ret))
return ret
}
const store = createStore(self => {
return {
count: 0,
increment() {
self.count++
}
}
})
console.log(store.count) // prints out 0
store.increment()
console.log(store.count) // prints out 1
Unfortunatelly the same is NOT working with TypeScript => types of store and self are inferred to {} instead of { count: number, increment(): void }.
TypeScript live demo: https://stackblitz.com/edit/typescript-sjuimf
function createStore<T>(init: (self: T) => T): T {
const ret: T = {} as T
// assume some change detector logic here
// (skipped to keep demo simple)
Object.assign(ret, init(ret))
return ret
}
const store = createStore(self => {
return {
count: 0,
increment() {
self.count++ // <------ type error!!!
}
}
}) // return type is {} instead of { count: number, increment(): void }
// Type errors in each of the following three lines!!!
console.log(store.count) // prints out 0
store.increment()
console.log(store.count) // prints out 1
The following demo shows an issue with TypeScript's type inference (tested with typescript@3.3.3333 and typescript@3.4.0-dev.20190226).
I do not know whether this should really be considered a bug but at least the same is working fine with Flow.
Pardon me, in case this has already been issued somewhere else in the past.
The following is working properly with Flow => types of
storeandselfare properly inferred as{ count: number, increment(): void }.Check here to see that the Flow code is fine.
Unfortunatelly the same is NOT working with TypeScript => types of
storeandselfare inferred to{}instead of{ count: number, increment(): void }.TypeScript live demo: https://stackblitz.com/edit/typescript-sjuimf