示例工程 27-dom-web-types

27-dom-web-types/04-nullability/src/main.ts

typescript · 0.5 KB

运行:27 · nullability

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

export function readValue(root: ParentNode): string {
  const input = root.querySelector<HTMLInputElement>('#name');
  if (input === null) return '(missing)';
  return input.value;
}
 
export function run(log: (msg: string) => void = console.log, root?: ParentNode): string[] {
  const scope = root ?? (typeof document === 'undefined' ? undefined : document);
  if (scope === undefined) throw new Error('本示例需要浏览器环境');
  const lines = [readValue(scope)];
  for (const line of lines) {
    log(line);
  }
  return lines;
}