0

I got the following code:

type MakeStyleConfig = {
  updateConfig?: {
    prevProps: Record<string, unknown>
    styledProps: string[]
  }
  [K: string]: unknown
}
type MakeStyles = (config?: MakeStyleConfig) => void

const makeStyles : MakeStyles = (config) => console.log(config)

let updateConfig: MakeStyleConfig | undefined
if (3/4 > -2) {
  updateConfig = {
    prevProps: {a:3},
    styledProps: ['size', 'shape']
  }
}
const state = {loaded: false}

// Why is this not working?
makeStyles({updateConfig: updateConfig, ...state})
//          ^^^^^^^^^^^^ this is marked as error by TSC

// This works OK as I expected:
makeStyles({updateConfig: {prevProps:{a:3}, styledProps:["s"], ...state}})

Why is the code marked as an error by TypeScript (v4.2.3)? It has the correct type and fields. The error is also pretty cryptic:

Type 'MakeStyleConfig | undefined' is not assignable to type '{ prevProps: Record<string, unknown>; styledProps: string[]; } | undefined'.
  Type 'MakeStyleConfig' is missing the following properties from type '{ prevProps: Record<string, unknown>; styledProps: string[]; }': prevProps, styledProps

Here is a link for the TS playground

1 Answer 1

1

You're trying to set updateConfig which is of type MakeStyleConfig to MakeStyleConfig.updateConfig which is of type

{
    prevProps: Record<string, unknown>,
    styledProps: string[]
}

The two are clearly not of the same type.

You should probably define a type which you can reuse for the updateConfig field on your MakeStyleConfig object, and change

let updateConfig: MakeStyleConfig | undefined

to be of that new type.

Example:

type UpdateConfig = {prevProps: Record<string, unknown>; styledProps: string[];}
type MakeStyleConfig = {
  updateConfig?: UpdateConfig | undefined
  [K: string]: unknown
}

// ...

let updateConfig: UpdateConfig | undefined;

// ...

makeStyles({updateConfig, ...state}) // this should now work
Sign up to request clarification or add additional context in comments.

3 Comments

my question was why is it marked as an error. Casting is not a nice solution, it could mask an underlying issue.
@sydd I've amended my answer as I initially misread your question.
You are right, I mixed up the object nesting. Thanks for the help!

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.