I've been trying to add webauthn to an Angular app. This MDN page outlines the necessary steps: https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API
The important thing is that using the APIs requires access to navigator.credentials
. However, Angular does not compile when I try to reference that. For example, this line of code:
await navigator.credentials.create({...});
...produces this error:
error TS2339: Property 'credentials' does not exist on type 'Navigator'.
Now I know I can do something like this:
declare global {
interface Navigator {
credentials: {
create(): void,
get(): void
}
}
}
But it's really tedious to have to write all that TypeScript for the entire CredentialsContainer
API. Besides, someone already did all that work in DefinitelyTyped
, right?
So I added @types/webappsec-credential-management
to my project with npm install --save-dev @types/webappsec-credential-management
.
Now Visual Studio Code knows what to do; I've got autocomplete and everything.
But Angular still won't compile. It gives the same error above.
What do I need to do to get Angular to recognize navigator.credentials
?
You can proceed as follow:
npm install --save-dev @types/webappsec-credential-management
then edit angular's <project>/src/tsconfig.app.json
{
...
"compilerOptions": {
...
"types": [
"@types/webappsec-credential-management"
]
...
}
It is necessary to edit angular's own tsconfig.app.json
as it will be used to compile angular's code. The root tsconfig.json
is used for bootstrapping and general (vscode) typescript config. So if you just add @types/webappsec-credential-management
to your types it will be recognised in your editor but it will be ignored by angular's very own compiler and thus creating this typing error:
error TS2339: Property 'credentials' does not exist on type 'Navigator'.
.
I was missing this at the top of my .ts file:
/// <reference types="@types/webappsec-credential-management" />
I also needed to ng update typescript
and ng update @angular/cli
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With