What is the TypeScript equivalent of “PropTypes.oneOf” (restrict a variable to subset of values)

后端 未结 3 772
南旧
南旧 2021-02-12 21:19

In React I can restrict a variable to subset of values, like

PropTypes.oneOf([\'Home\', \'About\']),

How do I do that in TypeScript?

3条回答
  •  长情又很酷
    2021-02-12 21:41

    You can use enum.

    Enums allow us to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases.

    enum vs union-type

    • Union types are a compile time concept
    • Enums are real objects that exist at runtime
    • You can iterate over an enum
    • ... see this question

    Example with 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 ...');
        }
    }
    

    Example with union type:

    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 ...');
        }
    }
    

提交回复
热议问题