在反应中,我可以将变量限制为值的子集。像
PropTypes.oneOf(['Home', 'About']),
我如何在打字稿中这样做。
PS:我没有反复使用打字稿。
答案 0 :(得分:7)
您可以通过定义union type:
来组合静态字符串(或任何常规类型)type SomeType = 'Home' | 'About';
或在界面内:
interface SomeType {
prop : 'Home' | 'About';
}
当然,你也可以结合其他类型:
type SomeType = string | boolean;
答案 1 :(得分:3)
联合类型中只有一种是联合类型,在您的情况下为string literal的联合。
您可以将字符串文字数组转换为字符串文字的并集,如下所示:
If you do have a const array or string you can define a type:
const menuList = ["Home", "About"] as const;
type menuName = typeof menuList[number] // "Home" | "About"
If you do already have a type with the array just do:
type menuList = ["Home", "About"];
type menuItem = menuList[number] // "Home" | "About"
答案 2 :(得分:2)
您可以使用enum
。
Enums允许我们定义一组命名常量。使用枚举可以更容易地记录意图,或创建一组不同的案例。
enum PostStatus {
DRAFT = "DRAFT",
READY = "READY",
PUBLISHED = "PUBLISHED",
}
class Post {
constructor(private status: PostStatus) {
this.status = status;
}
}
const myPost = new Post(PostStatus.DRAFT);
console.log(myPost);
function doStuff(postStatus: PostStatus) {
switch (postStatus) {
case PostStatus.DRAFT:
console.log('Still working on it');
break;
case PostStatus.PUBLISHED:
console.log('Done.');
break;
default:
console.log('Other ...');
}
}
type PostStatus = "DRAFT" | "READY" | "PUBLISHED";
class Post {
constructor(private status: PostStatus) {
this.status = status;
}
}
const myPost = new Post("DRAFT");
console.log(myPost);
function doStuff(postStatus: PostStatus) {
switch (postStatus) {
case "DRAFT":
console.log('Still working on it');
break;
case "PUBLISHED":
console.log('Done.');
break;
default:
console.log('Other ...');
}
}