类属性类型传递通过打字稿中的扩展 [英] class attribute type pass by extends in typescript
问题描述
在这种情况下,状态类型是正确的。
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;
// }
在情况2下,我不想更改状态类型我该怎么办?
I don't want to change the type of state in case 2. how should i do?
推荐答案
子类的方法和属性不是通过基类方法和属性进行上下文输入。这意味着TS无法从<$ c引用 state
的声明类型 Partial< S>
初始化属性时, Baz
中的$ c> Foo 基类。
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.
前一段时间,显然有一个相关的 PR 已被中止,因为在现实世界的应用程序中,缺点超过了优点。因此,如果您不想重新声明状态
,请在 Baz
中键入(游乐场):
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
}
,您可以传递 initialValue
用与 Baz
显式对应的类型声明:
, 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
}
其他链接
- 子类属性的上下文类型
- 子类方法的上下文类型
- TS规范上下文输入
- 相关问题:此处和此处
- Contextual typing for subclass properties
- Contextual typing for subclass methods
- TS spec contextual typing
- Related issues: here and here
这篇关于类属性类型传递通过打字稿中的扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!