在Typescript中仅包含特定值的数组

时间:2020-08-13 00:26:03

标签: typescript

我想要一个只能包含特定值的数组

例如socialService将是一个只能包含诸如facebooktwittergithublinkedin之类的值的数组。

目标是仅初始化在数组中传递的服务。

在打字稿中,如何指定只能包含某些值的数组?

1 个答案:

答案 0 :(得分:2)

您可以使用string literal type来实现。示例:

type SocialService = "facebook" | "twitter" | "github";
const arr: SocialService[] = [];
arr.push("github"); // Yay
arr.push("foo"); // Error