简体   繁体   中英

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, eg:

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, eg:

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

But if type (eg 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 XY-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 ).

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' }]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM