Search code examples
functiontypescripttypesparameterstypemaps

TypeScript Mapped Type Key/Values


I want to write a function with a parameter type guard that accepts the value from a K/V pair from an object or type...

type VodTreeName = {
  Movie: 'movie_vod',
  TV: 'tv_vod',
  VideoStore: 'video_store'
};

function test(something: VodTreeName) {
  // expecting something === 'movie_vod'
}

test(VodTreeName.Movie);
// 'VodTreeName' only refers to a type, but is being used as a value here. 

--or--

const VodTreeName = {
  Movie: 'movie_vod',
  TV: 'tv_vod',
  VideoStore: 'video_store'
};

function test(something: keyof typeof VodTreeName) {
  // expecting something === 'movie_vod'
}

test(VodTreeName.Movie);
// Argument of type 'string' is not assignable to parameter of type '"Movie" | "TV" | "VideoStore"'.

How else can I do this without having a type AND an object that I have to export/import to other modules?


Solution

  • You cannot use a type alias in runtime, there's no js equivalent for that.

    The test function in the 2nd snippet expects a key of VodTreeName but you are passing the value, it should be:

    function test(key: keyof typeof VodTreeName) {
        console.log(VodTreeName[key]);
    }
    
    test("Movie");
    

    If you want to use it like so:

    test(VodTreeName.Movie);
    

    Then you're basically looking for a string based enum, in which case check this thread: Create an enum with string values in Typescript and this issue: Proposal: String enums.