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?
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