Home > Net >  How to get a value of a type in typescript
How to get a value of a type in typescript

Time:10-07

Trying to get the value of a type in typescript where I only pass in the key of the type. Not exactly sure how to get the value out of a type in typescript, or if it is even possible. I am passing in a key, and I want to get the value out of it and then return the value as a negative number.

type ValueOf<T> = T[keyof T];

export type testingNumbers = {
  zero: '0px';
  xxxs: '4px';
  xxs: '8px';
  xs: '12px';
  s: '16px';
  m: '24px';
  l: '32px';
  xl: '40px';
  xxl: '64px';
  xxxl: '80px';
};

export type testingNumbersKeys = keyof testingNumbers;

export type testingNumbersValues = ValueOf<testingNumbers>;


/******NEW FILE******/


const getNegativeNumber = (margin: testingNumbersKeys) => {

let negativeMargin = margin.value(); //<----- What do I do here
return -negativeMargin;

}

Thanks,

CodePudding user response:

Types don't exist at runtime, so a type never has a value. But a value can have a type.

Which means the best you can do is to create a value, then infer a type from that.

export const testingNumbers = {
  zero: '0px',
  xxxs: '4px',
  xxs: '8px',
  xs: '12px',
  s: '16px',
  m: '24px',
  l: '32px',
  xl: '40px',
  xxl: '64px',
  xxxl: '80px',
} as const; 

export type TestingNumbers = typeof testingNumbers // get the type of the value
export type TestingNumbersValues = TestingNumbers[keyof TestingNumbers]


const getNegativeNumber = (margin: keyof TestingNumbers) => {
  let negativeMargin = testingNumbers[margin];
  return -negativeMargin;
}

See Playground

CodePudding user response:

The types get compiled away and don't exist at runtime. You can define a constant with your values and derive types from it like so.

Note: the mapping can be simplified by storing plain numbers to spare you from the runtime conversion of values to numbers.

type ValueOf<T> = T[keyof T];

const numbers =  {
  zero: '0px',
  xxxs: '4px',
  xxs: '8px',
  xs: '12px',
  s: '16px',
  m: '24px',
  l: '32px',
  xl: '40px',
  xxl: '64px',
  xxxl: '80px',
} as const;

export type testingNumbers = typeof numbers;

export type testingNumbersKeys = keyof testingNumbers;

export type testingNumbersValues = ValueOf<testingNumbers>;


/******NEW FILE******/


const getNegativeNumber = (margin: testingNumbersKeys) => {

let negativeMargin =  numbers[margin].split("px")[0]
return -negativeMargin;
}
  • Related