typescript-tutorial icon indicating copy to clipboard operation
typescript-tutorial copied to clipboard

字符串字面量类型有问题getElementById('hello')返回可能是null

Open jianjiachenghub opened this issue 5 years ago • 0 comments

type EventNames = 'click' | 'scroll' | 'mousemove';
function handleEvent(ele: Element, event: EventNames) {
    // do something
}

handleEvent(document.getElementById('hello'), 'scroll');  // 没问题
handleEvent(document.getElementById('world'), 'dbclick'); // 报错,event 不能为 'dbclick'

// index.ts(7,47): error TS2345: Argument of type '"dbclick"' is not assignable to parameter of type 'EventNames'.

修改function为

function handleEvent(ele: Element|null, event: EventNames) {
    // do something
}

jianjiachenghub avatar Dec 12 '19 05:12 jianjiachenghub