Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

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;
// }

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...