Is it possible to restrict typescript object to contain only properties defined by its class?

前端 未结 6 729
野趣味
野趣味 2020-11-27 06:32

Here is my code

async getAll(): Promise {
    return await dbQuery(); // dbQuery returns User[]
}

class User {
    id: number;
    na         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 07:02

    Following up on GregL's answer, I'd like to add support for arrays and make sure that if you've got one, all the objects in the array have no extra props:

    type Impossible = {
      [P in K]: never;
    };
    
    export type NoExtraProperties = U extends Array
      ? NoExtraProperties[]
      : U & Impossible>;
    

    Note: The type recursion is only possible if you've got TS 3.7 (included) or above.

提交回复
热议问题