1

I've gotten pretty close already.

I have a set of tuples:

type Schema =
    | ["link", string, string]
    | ["recentFiles", "byPath", string, number]
    | ["recentFiles", "byTime", number, string]

I created this type to iterate through all the prefixes:

type TuplePrefix<T extends unknown[]> = T extends [any, ...infer U]
    ? [] | [T[0]] | [T[0], ...TuplePrefix<U>]
    : []


type Prefixes = TuplePrefix<Schema>

And now I want to filter this list based on whether it is prefixed by another tuple.

type Result1 = Extract<Schema, ["recentFiles"]> // ❌ never
type Result2 = Extract<Schema, {0: "recentFiles"}> // ✅ ["recentFiles", "byPath", string, number] | ["recentFiles", "byTime", number, string]

So it appears this extraction doesn't work for tuples.

I tried mapping from tuple to the object representation, but TypeScript won't have it.

type TupleToObject<T extends any[]> = {[K in keyof T]: T[K]}

Any ideas how to make this work?

playground

1 Answer 1

2

A little bit of hardcoding, but this actually works:

type Ints = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "10" | "11" | "12" | "13" | "14" | "15" // | `${Ints}${Ints}`
type TupleToObject<T extends any[]> = Pick<T, Extract<keyof T, Ints>>

type Result = Extract<Schema, TupleToObject<["recentFiles"]>>
Sign up to request clarification or add additional context in comments.

1 Comment

To avoid hard-coding, you can now use type TupleToObject<T extends any[]> = Pick<T, keyof T & `${number}`>

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.