sydd
sydd

Reputation: 1946

TypeScript giving error on optional spread property

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

Upvotes: 0

Views: 125

Answers (1)

Ted
Ted

Reputation: 755

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

Upvotes: 1

Related Questions