Restrict generic types that extend map types


This Content is from Stack Overflow. Question asked by Howarto

How can I restrict a generic type with an object to allow only string values? Due to I put “extends” I get a generic type that extends also to numbers and symbols.

My decision to use generics is to create subtypes and add autocompletation for an event manager that works like:

const listenable = new Listenable<{ 'click': () => void }>();
listenable.addEventListener( 'click', () => {} );

An example that shows what I mean is:

type StringMapType = {
    [ key: string ]: Function

class Foo< MapType extends StringMapType > {

    bar< KeyType extends keyof MapType >( event: KeyType, callback: MapType[ KeyType ] ) {
        // Here the type of KeyType has to be of type `string` and
        // specifically is one of the defined MapType substrings.


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?