Home > Software engineering >  How do I add possible values to existing union type declared in standard library in TypeScript?
How do I add possible values to existing union type declared in standard library in TypeScript?

Time:12-11

Consider this PermissionName type declared in lib.dom.d.ts:

type PermissionName = "geolocation" | "notifications" | // More...

Can I somehow add a value to it from my own app.d.ts file? For example (code doesn't work):

declare global {

    type PermissionName = PermissionName | "local-fonts";

}

export {}

so that this code would work (this is the reason why I cannot declare new type, because other APIs is using this type)?

await navigator.permissions.query({
    name: "local-fonts"
});

Current workaround:

await navigator.permissions.query({
    name: <any>"local-fonts"
});

CodePudding user response:

What you need to augment is not PermissionName, but navigator.permissions.query

Playground

declare global {
  interface Permissions {
    query(permissionDesc: { name: 'local-fonts' }): Promise<PermissionStatus>;
  }
}
navigator.permissions.query({
  name: "local-fonts"
});

export { }
  • Related