Nav*_*med 9 google-chrome typescript typescript-typings angular
我按照https://web.dev/web-otp/上的说明在我的 Angular 应用程序中实现 Web OTP API。但是当添加下面的代码时,它会抛出错误:
const content = await window.navigator['credentials'].get({
otp: { transport: ['sms'] },
signal: abortController.signal
});
Run Code Online (Sandbox Code Playgroud)
这是错误消息:
Error TS2769 (TS) No overload matches this call.
Overload 1 of 2, '(options?: CredentialRequestOptions): Promise<CredentialType>', gave the following error.
Argument of type '{ otp: { transport: string[]; }; signal: AbortSignal; }' is not assignable to parameter of type 'CredentialRequestOptions'.
Object literal may only specify known properties, and 'otp' does not exist in type 'CredentialRequestOptions'.
Overload 2 of 2, '(options?: CredentialRequestOptions): Promise<Credential>', gave the following error.
Argument of type '{ otp: { transport: string[]; }; signal: AbortSignal; }' is not assignable to parameter of type 'CredentialRequestOptions'.
Object literal may only specify known properties, and 'otp' does not exist in type 'CredentialRequestOptions'.
Run Code Online (Sandbox Code Playgroud)
我已经@types/webappsec-credential-management
添加了,但我相信它尚未更新以支持otp
.
有什么解决方法吗?
这就是我解决问题的方法:
创建一个具有名称的新文件夹typings
并将其添加到typeRoots
intsconfig.json
"typeRoots": [
"typings",
"node_modules/@types"
],
Run Code Online (Sandbox Code Playgroud)
polyfills.d.ts
在文件夹中创建一个新文件typings
并将以下内容添加到该文件中:
interface CredentialRequestOptions {
otp: OTPOptions;
}
interface OTPOptions {
transport: string[];
}
Run Code Online (Sandbox Code Playgroud)
如果您想知道为什么我没有向界面添加其他属性,那是因为我已经有:
"types": [
"@types/webappsec-credential-management"
]
Run Code Online (Sandbox Code Playgroud)
并"@types/webappsec-credential-management": "^0.5.1",
在packages.json
.
的支持OTP
尚未添加,为了解决缺少的otp
属性,我利用了 TypeScript 的功能声明合并,现在 TypeScript 编译器将使用相同名称声明的这两个单独的声明(一个在 中定义node_modules/@types
,另一个在 中定义typings
)合并到一个定义中。
进一步阅读:https ://justintimecoder.com/how-to-polyfil-missing-types-in-typescript/
更新
以下是您可以添加到 Angular 组件以使其在您的应用程序中运行的函数:
async otpRequest() {
if ('OTPCredential' in window) {
const abortController = new AbortController();
let timer = setTimeout(() => {
abortController.abort();
}, 10 * 1000);
let o: CredentialRequestOptions = {
otp: { transport: ['sms'] },
signal: abortController.signal
};
const content = await window.navigator['credentials'].get(o);
//do what ever you want to do with the received code, probably send it to server
}
}
Run Code Online (Sandbox Code Playgroud)
调用此函数,然后发出http请求以在用户的移动设备上发送短信代码。
归档时间: |
|
查看次数: |
3013 次 |
最近记录: |