1

Given an array of tokens:

const myArray = <const>[
  {
    tokens: ["one", "two"],
  },
  {
    tokens: ["three"],
  },
  {
    tokens: [],
  },
  {
    somethingElse: {},
  },
];

I want to get a tuple for the all the different literals that the tokens property has. In the above example the result should be "one" | "two" | "three", however all my attempts yield any, unless I remove the third array item.

This is what I tried:

type ArrayItem = typeof myArray extends (infer T)[] ? T : never;
type ArrayItemWithTokens = Extract<ArrayItem, { tokens: [string] }>;
type TokenArrays = ArrayItemWithTokens extends { tokens: infer T } ? T : never;
type Token = TokenArrays extends (infer T)[] ? T : never;

1 Answer 1

2
const myArray = [
  {
    tokens: ["one", "two"],
  },
  {
    tokens: ["three"],
  },
  {
    tokens: [],
  },
  {
    somethingElse: {},
  },
] as const;

type Token = Extract<(typeof myArray)[number], {tokens: unknown}>['tokens'][number];
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! That works. Thanks. Didn't know you could put types within the [ ] op, makes so much sense though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.