shibata
shibata

Reputation: 21

How to configure Type correctly

help me! I've this FONT_SIZE. But I want to use HOGE_SIZE as an array. What are some ways to get it correctly like the FONT_SIZE?

const FONT_SIZE = {
  s: 13,
  m: 16,
  l: 20,
} as const;

type Hoge = {
  value: typeof FONT_SIZE[keyof typeof FONT_SIZE];
};

// (property) value: 13 | 16 | 20
const HOGE_SIZE = {
  s: { size: 13 },
  m: { size: 16 },
  l: { size: 20 },
} as const;

type HogeType = {
  value: typeof HOGE_SIZE[keyof typeof HOGE_SIZE];
};

// NG result!!
// (property) value: {
//     readonly size: 13;
// } | {
//     readonly size: 16;
// } | {
//     readonly size: 20;
// }

//  I hope -> (value: 13 | 16 | 20)

Upvotes: 1

Views: 34

Answers (1)

You need to add ['size']:

type Values<T>=T[keyof T]

// NG
const HOGE_SIZE = {
  s: { size: 13 },
  m: { size: 16 },
  l: { size: 20 },
} as const;

type HogeType = {
  value: Values<typeof HOGE_SIZE>['size'];
};

// OK
const FONT_SIZE = {
  s: 13,
  m: 16,
  l: 20,
} as const;

type Hoge = {
  value: Values<typeof FONT_SIZE>;
};


I have added Values utility type to make it less verbose

Upvotes: 1

Related Questions