microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.43k stars 12.42k forks source link

Type PermissionName for Permission API doesn't contain microphone and camera devices #59805

Open guiworks opened 1 month ago

guiworks commented 1 month ago

πŸ” Search Terms

microphone, camera, device, permission, state, API, navigator

βœ… Viability Checklist

⭐ Suggestion

In both files, webworker.generated.d.ts and dom.generated.d.ts in line 9361 and 27992.

The modification would be add two terms in the type PermissionName. 'camera' and 'microphone' to check access in both devices

πŸ“ƒ Motivating Example

  const checkForPermission = (type: PermissionName) => {
    navigator.permissions
      .query({
        name: type,
      })
      .then(permissionStatus => {
        // Will be 'granted', 'denied' or 'prompt':
        console.log(permissionStatus);
        // permissionStatus.state = 'granted'
        // Listen for changes to the permission state
        permissionStatus.onchange = () => {
          console.log(permissionStatus.state);
        };
      });
  };

  checkForPermission('microphone');
  checkForPermission('camera');

Expected behavior: 'microphone' and 'camera' should be valid types for PermissionName type.

Actual behavior: 'microphone' and 'camera' are not valid types for PermissionName type. Typescript is showing error: Argument of type '"microphone"' is not assignable to parameter of type 'PermissionName'.

πŸ’» Use Cases

  1. What do you want to use this for? Check if camera or microphone are enabled/disabled

  2. What shortcomings exist with current approaches? To type the promise from navigator.permission in typescript, we have to add a inclusion on type PermissionName like: { PermissionName } & { name: 'camera' | 'microphone' }.

  3. What workarounds are you using in the meantime? I'm using it: { PermissionName } & { name: 'camera' | 'microphone' }

xiBread commented 1 month ago

See https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1129

ehoogeveen-medweb commented 1 month ago

It appears that the name property of the PermissionDescriptor passed to Permissions#query is now simply specced as DOMString.

There is a permissions registry, but the number of entries is pretty limited, with 4 standardized permissions and 3 provisional permissions (as I write this).

So maybe it would be better for PermissionName to just become an alias of string (or preferably something that accepts any string but still autocompletes).

Edit: Ah, I missed the Why is this not an enum? note in the query method specification. Still, I'm not sure what you could base it on other than the provided tables which seem pretty limited. microphone for example isn't mentioned as a permission name in the spec at all.