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 ?
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; };
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With