class attribute type pass by extends in typescript

点点圈 提交于 2019-12-09 03:51:00

问题


In this case the type of state is correct.

export type Flatten<T> = T extends infer U ? { [K in keyof U]: U[K] } : never

class Foo<S> {
  state?: Partial<S>
}

class Bar<S> extends Foo<Flatten<S & { b: string }>> {
  async getInitialState(initialState: S) {
    return {
      ...initialState,
      b: 'bar'
    }
  }
}

const initialState = {
  a: 'baz'
}


class Baz extends Bar<typeof initialState> {
}

let baz = new Baz()
baz.state
// Partial<{
//   a: string;
//   b: string;
// }> | undefined

but in this case, the type of state will be override when assign a new value

class Baz extends Bar<typeof initialState> {
  state = initialState
}

let baz = new Baz()
baz.state
// {
//   a: string;
// }

I don't want to change the type of state in case 2. how should i do?


回答1:


Subclass methods and properties are not contextually typed by base class methods and properties. That means TS won't be able to refer to the declared type Partial<S> for state from Foo base class in Baz, when you initialize the property.

Some time ago, there apparently was a related PR which had been aborted, because cons outweighed the pros in real world applications. So, if you don't want to re-declare the state type in Baz like (Playground):

type State<S> = S & { b: string }

class Bar<S> extends Foo<State<S>> { }

class Baz extends Bar<typeof initialState> {
  state?: Partial<State<typeof initialState>> = initialState
}

, you could pass the initialValue declared with an explicit corresponding type to Baz:

const partialInitialState: Partial<State<typeof initialState>> | undefined = initialState

class Baz extends Bar<typeof initialState> {
  state = partialInitialState
}

Further links

  • Contextual typing for subclass properties
  • Contextual typing for subclass methods
  • TS spec contextual typing
  • Related issues: here and here


来源:https://stackoverflow.com/questions/58338400/class-attribute-type-pass-by-extends-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!