I know how to define a Position type class:
class Position {
  x: number = 0;
  y: number = 0;
}
But now I need to the x and y value is a integer with px as suffix like:
const position = {
  x: '1px',
  y: '2px'
}
How can I define a type like this in TypeScript?
You can try to use this approach:
type HeightUnit = '%' | 'px' | 'em' | 'vh';
type HeightProp = `${number}${HeightUnit}`
and result:
myHeight: HeightProp;
myHeight = '10px'  --- ok
myHeight = '10'  --- compilation error
See Template Literal Types for more info
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With