Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a custom type with `px` suffix

Tags:

typescript

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?

like image 307
hh54188 Avatar asked Sep 06 '25 03:09

hh54188


1 Answers

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

like image 95
Vitalii T Avatar answered Sep 08 '25 00:09

Vitalii T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!