여러 테스트 프레임워크가 키로 포함된 이 객체를 생각해 보겠습니다.

const testingFrameworks
  vitest: {
    label: "Vitest",
  },
  jest: {
    label: "Jest",
	},
  mocha: {
	  label: "Mocha",
  },
};

type TestingFramework = unknown;

Challenge

vitest, jest, mocha 키를 유니온 타입으로 추출해야 합니다.

다음과 같이 수동으로 유니온을 생성하면 테스트를 충족할 수 있습니다.

type TestingFramework = 'vitest' | 'jest' | 'mocha';

하지만 이상적인 해결책은 typeof 와 아직 보여드리지 않은 새로운 구문을 사용하여 객체에서 직접 키를 추출하여 유니온을 생성하는 것입니다.

나의 답

import { Equal, Expect } from '../helpers/type-utils';

const testingFrameworks = {
  vitest: {
    label: 'Vitest',
  },
  jest: {
    label: 'Jest',
  },
  mocha: {
    label: 'Mocha',
  },
};

type TestingFramework = keyof typeof testingFrameworks;

type tests = [Expect<Equal<TestingFramework, 'vitest' | 'jest' | 'mocha'>>];

Solution

Create Unions from Objects Using Two Operators

typeof 연산자만 사용하면 전체 객체를 타입으로 반환하게 되는데, 이는 우리가 원하는 것이 아닙니다.

testingFramework 객체의 키만으로 유니온 타입을 생성하려면, 각 최상위 키에 대해 반복하기 위해 keyof 연산자도 사용해야 합니다.

type TestingFramework = keyof typeof testingFrameworks;

이렇게 하면 테스트에서 예상한대로 “vitest" | "jest” | “mocha” 가 반환됩니다.

keyof 연산자는 KeyOf<...> 처럼 호출되는 것이 아닌 고유한 전용 키워드가 있다는 점에 유의하세요. 이는 typeof 와 마찬가지로 매우 low-level 이기 때문입니다.