重载函数中的字符串的变量防护

时间:2019-03-29 17:52:48

标签: typescript

字符串的防护在打字稿中不起作用。当我将函数的返回类型分配给变量out时,它将抱怨我不能为每个函数返回两次分配类型。错误是:第二个赋值“ out”时,后续变量声明必须具有相同的类型。

打字机游乐场link

  public events<K extends keyof GlobalEventHandlersEventMap>(
    eventType: K,
    // options?: EventsFnOptions,
  ): Stream<GlobalEventHandlersEventMap[K]>
  public events(eventType: "resize"): Stream<windowSize>{
    let stream
    // let out
    // if (eventType == "resize") {
    if (eventType == "resize") {

      stream = fromEvent(window, 'resize')
        .map(windowSize)
        .startWith(windowSize())
        .remember();
      var out: DevToolEnabledSource & Stream<windowSize> = adapt(stream)
      out._isCycleSource = this._name
    } else {
      stream = fromEvent(
        window,
        eventType,
      )
      var out: DevToolEnabledSource & Stream<Event> = adapt(stream)
      out._isCycleSource = this._name
    }
    return out;
  }

1 个答案:

答案 0 :(得分:1)

我将代码简化为仅相关部分,并遗漏了缺少的定义,我更改了events方法以返回Stream<windowSize | Event>以匹配两种可能的返回类型之一。

我还为out设置了一个const变量,该变量仅在该范围内是本地的,然后直接从那里返回。

class Stream<T> {}

class DevToolEnabledSource {
  public _isCycleSource: string; 
}

interface windowSize {
  width: number,
  height: number,
}

function adapt(x: any): any {}

class example {
  private _name: string;

  public events(eventType: "resize"): Stream<windowSize | Event> {
    let stream;
    if (eventType == "resize") {
      const out: DevToolEnabledSource & Stream<windowSize> = adapt(stream)
      out._isCycleSource = this._name
      return out;
    } else {
      const out: DevToolEnabledSource & Stream<Event> = adapt(stream)
      out._isCycleSource = this._name
      return out;
    }
  }
}

TypeScript Playground

回答仅须声明out一次的问题:是的,这是可能的。

let out: Stream<windowSize | Event>;
...
// assign out one way or the other
...
return out;