Typed Dialog Element Confirm Flow

Wire a confirm dialog with typed event listeners: cancel is cancelable, close(reason) sets returnValue, and querySelector narrows type and null in one generic.

TypescriptData Fetching

Code

typescriptsnippet
25 lines
type ConfirmChoice = 'confirmed' | 'cancelled';

function wireConfirm(dialog: HTMLDialogElement, onChoice: (choice: ConfirmChoice) => void): void {
  // Esc 与点击 ::backdrop 触发 cancel;preventDefault 后自行决定关闭语义
  dialog.addEventListener('cancel', (event: Event) => {
    event.preventDefault();
    dialog.close('cancelled');
  });
  // close 事件异步派发:returnValue 同步就绪,回调在任务队列里收到通知
  dialog.addEventListener('close', () => {
    onChoice(dialog.returnValue === 'confirmed' ? 'confirmed' : 'cancelled');
  });
}

// querySelector 泛型一次完成元素类型与空值收窄
const dialog = document.querySelector<HTMLDialogElement>('#confirm-dialog');

if (dialog) {
  wireConfirm(dialog, (choice) => console.log('result:', choice));
  dialog.showModal();
  // 真实页面里由按钮触发;演示直接以 returnValue 收口
  dialog.close('confirmed');
  console.log('open:', dialog.open);
  console.log('returnValue:', dialog.returnValue);
}

How the snippet works

Count the function wireConfirm as the entire surface area of Typed Dialog Element Confirm Flow.

Points of care

  • document exist only in browsers — a Node runtime has no shims for them out of the box.

Using it

The primary signature is function wireConfirm(dialog: HTMLDialogElement, onChoice: (choice: ConfirmChoice)

The demo output is labeled (result:, open:, returnValue:), so every printed line has a specific operation behind it.

Key statements

dialog.addEventListener('cancel', (event: Event) => {
event.preventDefault();
dialog.close('cancelled');
});
dialog.addEventListener('close', () => {
onChoice(dialog.returnValue === 'confirmed' ? 'confirmed' : 'cancelled');
});

Interactive Tools for This Topic

FAQ

Does Typed Dialog Element Confirm Flow run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.