Your problem is that state
is being inferred as an array instead of as a tuple. There are several ways around this, as detailed in this answer. I'll just present one of them here.
Assuming you are using TypeScript 3.0 or above, you can define the following tuple()
helper function which takes any number of arguments and returns a tuple of those arguments:
type Narrowable = string | number | boolean | undefined | null | void | {};
const tuple = <T extends Narrowable[]>(...t: T)=> t;
Then, you can use it inside your FieldPadding
class definition:
export default class FieldPadding extends React.Component<IPaddingProps, IFieldSate> {
readonly state = {
value: tuple(0, 0, 0, 0)
}
}
and that gives value
the type [0, 0, 0, 0]
, a tuple type with four elements of numeric literal type 0
.
UPDATE:
So you want state
to be readonly
but you want to change the values of state.value
from 0
to other numbers?
In that case you want value
to be type [number, number, number, number]
, which is wider than [0, 0, 0, 0]
but narrower than number[]
. You can annotate that yourself, which I'd recommend if you want such strict control over the type:
export default class FieldPadding extends React.Component<IPaddingProps, IFieldSate> {
readonly state = {
value: [number, number, number, number] = [0, 0, 0, 0]
}
}
You could also do
export default class FieldPadding extends React.Component<IPaddingProps, IFieldSate> {
readonly state = {
value: tuple(0 as number, 0 as number, 0 as number, 0 as number)
}
}
or
const z: number = 0;
export default class FieldPadding extends React.Component<IPaddingProps, IFieldSate> {
readonly state = {
value: tuple(z, z, z, z)
}
}
or even make a less narrowing tuple()
function
const wideTuple = <T extends any[]>(...t: T) => t;
export default class FieldPadding extends React.Component<IPaddingProps, IFieldSate> {
readonly state = {
value: wideTuple(0, 0, 0, 0)
}
}
Any of those should work for you. The short answer to the question as asked, though, is that you need a tuple type, not an array. Exactly how you get that is up to you.
Hope that helps; good luck!