Leon Adler
Leon Adler

Reputation: 3341

How can you generate a mapped type that is a tuple type?

Let's assume I have an input which adheres to a defined type:

interface Person {
    name: string;
    age: number;
}

Now, I want a function to accept an array of key-value pairs, e.g.:

function acceptsPersonProperties(tuple: Array<PersonTuple>) { ... }

// this should be fine:
acceptsPersonProperties([['name', 'Bob'], ['age', 42]]);

// this should give a compile-time error:
acceptsPersonProperties([['name', 2], ['age', 'Bob']]);

Of course, I can type this manually, e.g.:

type PersonTuple = ['name', string] | ['age', number];

But if type (e.g. Person) is a template variable, how can the tuple be expressed as a mapped type?

function acceptsPropertiesOfT<T>(tuple: Array<MappedTypeHere<T>>) { ... }

To avoid an X-Y-Problem, the real use case is this:

let request = api.get({
    url: 'folder/1/files',
    query: [
        ['fileid', 23],
        ['fileid', 47],
        ['fileid', 69]
    ]
});

which resolves to "/api/folder/1/files?fileid=23&fileid=47&fileid=69", but which I want to type, so it does not allow extra properties (file_id) and checks types (no string as fileid).

Upvotes: 6

Views: 711

Answers (1)

bcherny
bcherny

Reputation: 3172

You can't do it with tuple types. The right side of the tuple will always get generalized to a union of all possible values in Person.

You can, however, make it work if you change your API slightly:

interface Person {
  name: string;
  age: number;
}

function acceptsPersonProperties(tuple: Partial<Person>[]) { }

// this should be fine:
acceptsPersonProperties([{ name: 'Bob' }, { age: 42 }]);

// this should give a compile-time error:
acceptsPersonProperties([{ name: 2 }, { age: 'Bob' }]);

Upvotes: 4

Related Questions