typescript restrict count of object's properties

前端 未结 3 1461
甜味超标
甜味超标 2020-11-30 15:05

Is it possible to restrict the count of object properties, say I want to restrict object have only one string propery (with any name), I can do:

{[index: stri         


        
3条回答
  •  被撕碎了的回忆
    2020-11-30 15:36

    Because this question has been marked as a duplicate of this one, let me answer here.

    Check if a type is a union

    /**
     * @see https://stackoverflow.com/questions/53953814/typescript-check-if-a-type-is-a-union/53955431
     */
    type IsSingleton =
      [T] extends [UnionToIntersection]
        ? true
        : false
    
    /**
     * @author https://stackoverflow.com/users/2887218/jcalz
     * @see https://stackoverflow.com/a/50375286/10325032
     */
    type UnionToIntersection =
      (Union extends any
        ? (argument: Union) => void
        : never
      ) extends (argument: infer Intersection) => void
        ? Intersection
      : never;
    

    Allow only singleton types

    type SingletonOnly =
      IsSingleton extends true
        ? T
        : never
    

    Restrict a function to accept only a singleton type

    declare function foo(s: SingletonOnly): void
    
    declare const singleton: 'foo';
    foo(singleton);
    
    declare const union: "foo" | "bar";
    foo(union); // Compile-time error
    

    TypeScript Playground

提交回复
热议问题