首页 > 解决方案 > 函数具有显式返回时的窄推断类型

问题描述

看下面的代码:

type Shape = null | string | string[] | { [key: string]: string | string[] }

interface ICfg<InShape extends Shape, OutShape extends Shape> {
  shapes?: readonly [InShape, OutShape]
  handle?(x: NonNullable<this["shapes"]>[0]): NonNullable<this["shapes"]>[1]
}

function apply<InShape extends Shape, OutShape extends Shape>(cfg: () => ICfg<InShape, OutShape>) {
  return cfg()
}

const shape = {
  type: "abc",
  date: "qwe",
}

var x = apply(() => ({
  shapes: [shape, shape],
  handle: x => null as any,
}))

变量x的类型是ICfg<{ type: string; date: string; }, { type: string; date: string; }>完美的。

但是让我们稍微改变一下函数语法: from () => ({ ... })to () => { return { ... } }:

var y = apply(() => {
  return {
    shapes: [shape, shape],
    handle: x => null as any,
  }
})

现在的类型yICfg<Shape, Shape>,这很糟糕。

实际上我有更多的困难,因为我真的需要变量shape在函数内部(实际上函数apply有参数并且shape基于它们):

var z = apply(() => {
  const shape = {
    type: "abc",
    date: "qwe",
  }

  return {
    shapes: [shape, shape],
    handle: x => null as any,
  }
})

此代码ICfg<Shape, Shape>对变量产生相同的结果z

我需要变量z来拥有ICfg<{ type: string; date: string; }, { type: string; date: string; }>x这样的类型。有没有办法在没有明确指定泛型参数的情况下实现这一点apply

操场上的完整代码。

标签: typescriptgenerics

解决方案


推荐阅读