How to get a value of a type in typescript

Issue

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,

Solution

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

Answered By – Alex Wayne

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published