class 在打字稿中扩展传递的属性类型

class attribute type pass by extends in typescript

在这种情况下,状态类型是正确的。

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

但在这种情况下,状态类型将在分配新值时被覆盖

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

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

我不想改变情况2的状态类型,我该怎么办?

Subclass 方法和属性不是 contextually typed 基础 class 方法和属性。这意味着当你初始化 属性.

前段时间,好像有个相关的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
}

,你可以将用显式对应类型声明的 initialValue 传递给 Baz:

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

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

更多链接