0

edit:

IMPORTANT

As @jcalz mentions, the example as is, it is wrong, since if there is any State defined on child component, than the initialization is wrong.

As a way to ignore it, it is possible to use as key as @sychd mention, but remember this example is actually an error


I'm struggling with initializing state with typescript

So I have a component that has variable state, i.e. the component has state, but the children can also define (extra) state.

This brings the problem of trying to initialise the parent state with only the part that it knows of.

This piece of code can explain the issue

interface Default {
  something: boolean
}

class A<State> {
  state: State & Default = {
    something: false
  }
}

check: Typescript Playground

So above we see that state complains about that Default type is not assignable to Default & State

Any ideas how to solve this?

2
  • 2
    Looks like a valid error to me; you haven't initialized state to a valid State & Default. When in the code does it get set properly? Commented Jul 11, 2018 at 16:08
  • I was attempting to set it partially, but it makes sense if I initialise it partially it is not a valid object of that type. Commented Jul 12, 2018 at 5:26

1 Answer 1

1

As about your code - the trick is as State & Default because TS see {something: false} as some object. But

class A<State> {
  state: State & Default = {
    something: false
  } as  State & Default;
}

will be ok. Also, probably it will suit your needs, you can try extandable generics:

interface Default {
  something: boolean
}
interface State extends Default {
  something: boolean,
}

class A<T extends Default> {
  state: T = {
    something: false
  } as T;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Using a type assertion (as) is only a good idea if the developer knows that the assertion is or will be valid, since it relaxes the compiler's type checking. The code as it stands looks like it should be an error, unless @mloureiro adds more information about how state will be properly initialized.
@jcalz, yep. But declaration object with params(as in code snippet) will not suit any type with same fields (except state: {something: boolean} = {something: false}), so explicit cast is required. Otherwise, he can pass set param via constructor or via setter, so explicit cast can (and should) be avoided

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.