NDEFReader in TypeScript



我正在React中尝试使用NDEFReader()进行NFC扫描/写入。该功能适用于Chrome 81(您可以在下面的链接上在Chrome测试版中在手机上试用(。

GoogleChromeFcSample,WhatWebCanDoTodayNfc

要启用此功能,您需要进入chrome://flags/并启用实验Web平台功能

问题是我无法在React中实现这一点。我使用带有TypeScript和控制台输出的create-react应用程序:

找不到名称"NDEFReader">

我认为这会导致网络包检查。我已经尝试更改tsconfig.json中的一些设置,但没有成功。有人知道如何启用实验性js/ts编译来启用此功能吗?

Web NFC人员在https://github.com/w3c/web-nfc/blob/gh-pages/web-nfc.d.ts

// Type definitions for Web NFC
// Project: https://github.com/w3c/web-nfc
// Definitions by: Takefumi Yoshii <https://github.com/takefumi-yoshii>
// TypeScript Version: 3.9
// This type definitions referenced to WebIDL.
// https://w3c.github.io/web-nfc/#actual-idl-index
interface Window {
NDEFMessage: NDEFMessage
}
declare class NDEFMessage {
constructor(messageInit: NDEFMessageInit)
records: ReadonlyArray<NDEFRecord>
}
declare interface NDEFMessageInit {
records: NDEFRecordInit[]
}
declare type NDEFRecordDataSource = string | BufferSource | NDEFMessageInit
interface Window {
NDEFRecord: NDEFRecord
}
declare class NDEFRecord {
constructor(recordInit: NDEFRecordInit)
readonly recordType: string
readonly mediaType?: string
readonly id?: string
readonly data?: DataView
readonly encoding?: string
readonly lang?: string
toRecords?: () => NDEFRecord[]
}
declare interface NDEFRecordInit {
recordType: string
mediaType?: string
id?: string
encoding?: string
lang?: string
data?: NDEFRecordDataSource
}
declare type NDEFMessageSource = string | BufferSource | NDEFMessageInit
interface Window {
NDEFReader: NDEFReader
}
declare class NDEFReader extends EventTarget {
constructor()
onreading: (this: this, event: NDEFReadingEvent) => any
onreadingerror: (this: this, error: Event) => any
scan: (options?: NDEFScanOptions) => Promise<void>
write: (
message: NDEFMessageSource,
options?: NDEFWriteOptions
) => Promise<void>
}
interface Window {
NDEFReadingEvent: NDEFReadingEvent
}
declare class NDEFReadingEvent extends Event {
constructor(type: string, readingEventInitDict: NDEFReadingEventInit)
serialNumber: string
message: NDEFMessage
}
interface NDEFReadingEventInit extends EventInit {
serialNumber?: string
message: NDEFMessageInit
}
interface NDEFWriteOptions {
overwrite?: boolean
signal?: AbortSignal
}
interface NDEFScanOptions {
signal: AbortSignal
}

这与Webpack检查或tsconfig或"实验性JavaScript"无关。

只是NDEFReader()没有可用的类型,所以TypeScript认为您有拼写错误。

您可以在源树中使用类似extra-globals.d.ts的文件(只要是.d.ts,名称就无关紧要(来存根NDEFReader的类型。这基本上告诉TypeScript,全局窗口接口有一个额外的字段NDEFReader,其类型您并不知道:

declare global {
interface Window {
NDEFReader: any;
}
}
export {};

最新更新