Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Mapped types with Interface

When trying to use mapped types with interface, i get a weird error - which makes me think its not possible to use them together at all..

See identical type and interface declarations:

type AllWorks<T> = {
    [K in keyof T]: T[K];
}

interface DoesNotWork<T> {
    [K in keyof T]: T[K];
}

While first one works as expected, second one gives the TS error:

[ts] A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
[ts] Member '[K in keyof' implicitly has an 'any' type.
[ts] Cannot find name 'keyof'.

So my question is - is it even possible to map over interfaces ? if yes - then how ?

like image 479
c69 Avatar asked Mar 14 '18 17:03

c69


People also ask

What is mapped type in TypeScript?

A mapped type is a generic type which uses a union of PropertyKey s (frequently created via a keyof ) to iterate through keys to create a type: type OptionsFlags < Type > = { [ Property in keyof Type ]: boolean; };

Does TypeScript have a Map type?

TypeScript map is a new data structure added in ES6 version of JavaScript. It allows us to store data in a key-value pair and remembers the original insertion order of the keys similar to other programming languages. In TypeScript map, we can use any value either as a key or as a value.

Are types and interfaces the same TypeScript?

Key Differences between TypeScript type vs interface Whereas interfaces are defined as a declaration of the only object type, which means the interfaces are restricted to only object type and do not support any other type for declaration. But we can say that interfaces have more capabilities than types in typescript.

How do I use maps in TypeScript?

Use Map type and new keyword to create a map in TypeScript. let myMap = new Map<string, number>(); To create a Map with initial key-value pairs, pass the key-value pairs as an array to the Map constructor.


1 Answers

So far in TypeScript (as of version 2.7.2), union type signatures in interfaces are not allowed and instead mapped types should be used (as you correctly have).

Docs.

like image 186
Behrooz Avatar answered Sep 19 '22 16:09

Behrooz