TypeScript 中的 NDEFReader

Dal*_*ola 3 javascript nfc reactjs webnfc

我正在尝试NDEFReader()在 React 中用于 NFC 扫描/写入。此功能可在 Chrome 81 上使用(您今天可以通过下面的链接在移动设备上的 Chrome 测试版中尝试该功能)。

GoogleChromeNfcSampleWhatWebCanDoTodayNfc

要启用此功能,您需要进入chrome://flags/并启用Experimental Web Platform features

问题是我无法在 React 中完成这项工作。我将 create-react-app 与 TypeScript 和控制台输出结合使用:

找不到名称“NDEFReader”

我认为这会导致 webpack 检查。我已经尝试更改 tsconfig.json 中的一些设置,但没有任何效果。有谁知道如何启用实验性 js/ts 编译以启用此功能?

Fra*_*ort 7

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

// 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
}
Run Code Online (Sandbox Code Playgroud)