Typescript通用回调对象的严格性

4

我不明白为什么下面的代码没有报错

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不正确?


问题是什么?如果您认为这是错误的,我会在TypeScript的GitHub页面上提出问题。为什么以下内容不会引发错误?因为TypeScript编译器不知道¯_(ツ)_/¯。 - Liam
为什么format中的回调函数需要显式设置返回类型才能显示错误,而第一个情况却没有显示错误?OP觉得当format函数明确指示返回类型时,不应该需要两次输入Test(后一种情况)。 - Nishant
@Liam 嗨 - 是的,我已经澄清了我的问题 - 这是一个预期的 typescript 限制吗? - amwill04
1个回答

1

过度属性检查未被触发,因为callback没有显式类型注释。TypeScript 推断其类型为() => { foo: string; bar: string },该类型可分配给Callback<Test>

看一下这个例子:

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

{{链接1:游乐场}}


谢谢。这是否意味着只要扩展了“Test”,它就会通过?因此,我需要明确设置返回类型吗? - amwill04
只有在存在显式目标类型时,对象字面量才会进行过度属性检查。 - Aleksey L.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接