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

前端 未结 6 745
野趣味
野趣味 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

    Typescript uses structural typing instead of nominal typing to determine type equality. This means that a type definition is really just the "shape" of a object of that type. It also means that any types which shares a subset of another type's "shape" is implicitly a subclass of that type.

    In your example, because a User has all of the properties of GetAllUserData, User is implicitly a subtype of GetAllUserData.

    To solve this problem, you can add a dummy property specifically to make your two classes different from one another. This type of property is called a discriminator. (Search for discriminated union here).

    Your code might look like this. The name of the discriminator property is not important. Doing this will produce a type check error like you want.

    async function getAll(): Promise {
      return await dbQuery(); // dbQuery returns User[]
    }
    
    class User {
      discriminator: 'User';
      id: number;
      name: string;
    }
    
    class GetAllUserData {
      discriminator: 'GetAllUserData';
      id: number;
    }
    

提交回复
热议问题