Home > Enterprise >  Enforce excess property check on function return type?
Enforce excess property check on function return type?

Time:12-29

In the following example, TypeScript compiler will not complain about returning an object of type UserProfile from a function that has a return type UserProfileWithNoPermissions:

interface UserProfile {
    name: string,
    age: number,
    permissions: string[],
}

type UserProfileWithNoPermissions = Omit<UserProfile, 'permissions'>

const getUser = (): UserProfileWithNoPermissions => {
    const profile: UserProfile = ({
        name: '',
        age: 0,
        permissions: ['canView'],
    })

  return profile

};

I understand that this is because of TS skipping excess property check in this case (as opposed to object literal for example). But (subjectively) such code looks strange... Is there any relatively non-hacky way to make TS compiler complain about profile object having permissions property? Is it even a good idea to do that?

CodePudding user response:

EPC comes into play just for fresh objects:

interface UserProfile {
    name: string,
    age: number,
    permissions: string[],
}

type UserProfileWithNoPermissions = Omit<UserProfile, 'permissions'>

const getUser = (): UserProfileWithNoPermissions => {
    return {
        name: '',
        age: 0,
        permissions: ['canView'], // <-- EPC error
    })
};

Therefore I think you'd need exact types.

CodePudding user response:

You could explicitly forbid the property permissions from appearing in an object with the UserProfileWithNoPermissions type.

type UserProfileWithNoPermissions = 
  Omit<UserProfile, 'permissions'> & { permissions?: undefined }

Though this will not check for any other excess properties.


Playground

  • Related