xcatliu / typescript-tutorial

TypeScript 入门教程
https://ts.xcatliu.com
10.44k stars 1.33k forks source link

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

Open jianjiachenghub opened 4 years ago

jianjiachenghub commented 4 years ago
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
}