【问题标题】:Typescript generic callback object strictness打字稿通用回调对象严格性
【发布时间】:2021-02-11 19:31:20
【问题描述】:

我很难理解为什么以下内容不会引发错误

type Callback<T> = () => T

function format<V>(callback: Callback<V>): V {
    return callback()
}

type Test = {foo: string}

format<Test>(() => {
    return {
        foo: 'hello',
        bar: 'dd' // I expect an error to be here as `bar` does not exist on type Test
    }
})

// if I explicitly set the return type in the callback then I get the correct error

format<Test>((): Test => {
    return {
        foo: 'hello',
        bar: 'dd' // this now errors as I have set the return type.
    }
})

我不禁觉得这是重复?

这是typescript 的限制并且“符合预期”,还是我的types 不正确?

【问题讨论】:

  • 有什么问题?如果您认为这是错误的,我会在 GitHub 页面上针对 typescript 提出问题。 为什么下面没有抛出错误因为打字稿转译器没有¯\_(ツ)_/¯
  • 为什么format中的回调函数需要显式设置返回类型才能显示错误,为什么第一种情况没有显示错误?当format 函数清楚地表明返回类型是什么时,OP 感觉不需要输入两次Test(后一种情况)。
  • @Liam 嘿-是的,我已经澄清了我的问题-这是预期的typescript 限制。

标签: typescript typescript-generics


【解决方案1】:

Excess property checking 不会被触发,因为callback 没有明确的类型表示法。 Typescript 将其类型推断为() =&gt; { foo: string; bar: string },可分配给Callback&lt;Test&gt;

看看这个例子:

type Callback<T> = () => T

type Test = { foo: string }

const extendedCallback = () => ({ foo: 'hello', bar: 'bar' }) // inferred as () => { foo: string; bar: string }

const callback: Callback<Test> = extendedCallback // assignment is valid

Playground

【讨论】:

  • 谢谢。这是否意味着只要它扩展Test 它就会通过?因此我需要显式设置返回类型呢?
  • 对象字面量只有在有明确的目标类型时才会进行过多的属性检查。
猜你喜欢
  • 2018-07-27
  • 2017-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 2017-03-31
相关资源
最近更新 更多