type padding = [number, number, number, number]
interface IPaddingProps {
defaultValue?: padding
className?: string
disabled?: boolean
min?: number
max?: number
onChange?: (value: number | string) => void
}
interface IFieldSate {
value: padding
}
export default class FieldPadding extends React.Component<IPaddingProps, IFieldSate> {
readonly state = {
value: [0, 0, 0, 0]
}
constructor(props: IPaddingProps) {
super(props)
if (props.defaultValue) {
this.state.value = [...props.defaultValue]
}
}
}
I get an error at state
saying:
Type 'number[]' is missing the following properties from type '[number, number, number, number]': 0, 1, 2, 3?
type padding = [number, number, number, number]
interface IPaddingProps {
defaultValue?: padding
className?: string
disabled?: boolean
min?: number
max?: number
onChange?: (value: number | string) => void
}
interface IFieldSate {
value: padding
}
export default class FieldPadding extends React.Component<IPaddingProps, IFieldSate> {
readonly state = {
value: [0, 0, 0, 0]
}
constructor(props: IPaddingProps) {
super(props)
if (props.defaultValue) {
this.state.value = [...props.defaultValue]
}
}
}
I get an error at state
saying:
Type 'number[]' is missing the following properties from type '[number, number, number, number]': 0, 1, 2, 3?
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?