0

When

function StyleMixin(base: React.CSSProperties) {}




StyleMixin({
    fontWeight: 'bold',
    lineHeight: 1,
    textAlign: 'center',
    [someVariable]: {
        fontSize: '1rem',
    }
}

In [someVariable], it says

TS2345: Argument of type '{ fontWeight: "bold"; lineHeight: number; textAlign: "center"; ...' is not assignable to parameter of type 'CSSProperties'. Object literal may only specify known properties, and '[someVariable]' does not exist in type 'CSSProperties'.

How to fix this?

Taichi
  • 2,297
  • 6
  • 25
  • 47

1 Answers1

2

This happens if someVariable is a string literal type that is not a property of React.CSSProperties

const someVariable = "nonExistentProperty";
StyleMixin({
    fontWeight: 'bold',
    lineHeight: 1,
    textAlign: 'center',
    [someVariable]: {
        fontSize: '1rem',
    }
})

It will actually work if someVariable is a variable not a constant (ie. declared with let or var).

I suggest making sure you actually want to add a property not in CSSProperties (if you are not seeing the full error message use "noErrorTruncation": true in tsconfig.json)

If you actually want StyleMixin to be an object that can add extra properties to CSSProperties you can use a generic parameter in the function:

function StyleMixin< T extends React.CSSProperties>(base: T) {}
const someVariable = "nonExistentProperty";
StyleMixin({
    fontWeight: 'bold',
    lineHeight: 1,
    textAlign: 'center',
    [someVariable]: {
        fontSize: '1rem',
    }
})
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357