Skip to content

Issue with type inference #30105

@mcjazzyfunky

Description

@mcjazzyfunky

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions