【问题标题】:Typescript type for user generated object用户生成对象的打字稿类型
【发布时间】: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 时。它会在没有编译器错误的情况下静默中断。

如果我限制类型,我将需要为我想要发送的每种类型创建对象。

但如果我使用anyObject,它将允许PromiseFunctionDate

您有解决方法吗?可能是避免内置 javascript 对象的泛型类型。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以使用条件类型来实现这一点;在这里查看答案https://stackoverflow.com/a/49262929/4800808

    【讨论】:

      猜你喜欢
      • 2017-03-31
      • 2018-09-15
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 2020-10-11
      相关资源
      最近更新 更多