【问题标题】:class attribute type pass by extends in typescript类属性类型通过在打字稿中扩展
【发布时间】:2019-10-11 09:35:26
【问题描述】:

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

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的状态类型,我该怎么办?

【问题讨论】:

    标签: typescript class generics types extends


    【解决方案1】:

    子类方法和属性不是contextually typed 基类方法和属性。这意味着当您初始化属性时,TS 将无法从 Foo 基类 Baz 中引用声明的类型 Partial&lt;S&gt;state

    前段时间,显然有一个相关的PR 已被中止,因为cons outweighed the pros 在现实世界的应用程序中。因此,如果您不想重新声明state,请输入Baz,例如(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
    }
    

    更多链接

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-11
      • 2020-08-18
      • 1970-01-01
      • 2022-01-11
      • 2018-02-10
      • 2018-01-18
      • 2014-06-11
      • 1970-01-01
      相关资源
      最近更新 更多