TypeScript映射类型键/值

时间:2017-03-17 00:23:04

标签: function typescript types parameters typemaps

我想编写一个带参数类型guard的函数,该函数接受来自对象或类型的K / V对的值...

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. 

- 或 -

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"'.

如果没有我必须导出/导入到其他模块的类型和对象,我还能如何做到这一点?

1 个答案:

答案 0 :(得分:2)

你不能在运行时使用类型别名,没有相应的js。

第二个代码段中的test函数需要一个VodTreeName的密钥,但是您传递的值应该是:

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

test("Movie");

如果您想这样使用它:

test(VodTreeName.Movie);

然后你基本上找了一个基于字符串的枚举,在这种情况下检查这个帖子:Create an enum with string values in Typescript和这个问题:Proposal: String enums