【发布时间】:2020-10-29 21:00:51
【问题描述】:
我最近偶然发现了一个问题。
在打字稿中,如果我们创建应该接受用户生成对象的函数。
我们使用any。
// will pass object to google-analytics
function sendGoogleAnalytics(a: any){
//should pass any user-generated object but not promise, Date, Array
PostRequestToGA(a);
}
// Expected Example:
sendGoogleAnalytics('asdf');
sendGoogleAnalytics({hello: 'world'});
sendGoogleAnalytics({anyKey: 'world', another: 'world2'});
// but should prevent sending Promise, Date, or built-in javascript object.
// example below, should be prevented at compile time
sendGoogleAnalytics(fetch('google.com'))
sendGoogleAnalytics(()=>{})
sendGoogleAnalytics(new Date())
但这是等待发生的错误。
例如,当我不小心通过了 Promise 时。它会在没有编译器错误的情况下静默中断。
如果我限制类型,我将需要为我想要发送的每种类型创建对象。
但如果我使用any 或Object,它将允许Promise、Function、Date。
您有解决方法吗?可能是避免内置 javascript 对象的泛型类型。
【问题讨论】:
标签: typescript