代码之家  ›  专栏  ›  技术社区  ›  jjjjjjjjjjjjjjjjjjjj

是否可以使用函数类型强制执行“无未知属性”?

  •  2
  • jjjjjjjjjjjjjjjjjjjj  · 技术社区  · 4 年前

    返回类型 返回类型 对象文字只能指定已知属性 .

    // Type '{ status: string; bar: string; }' is not assignable to type '{ status: string; }'.
    // Object literal may only specify known properties, and 'bar' does not exist in type '{ status: string; }'.(2322)
    const foo = function(): {status: string} {
        return {
            status: '200 OK',
            bar: 'baz', // Problem
        }
    }
    

    ,在从返回的对象中忽略已知属性时,我们将收到一个类型错误,指出缺少已知属性:

    // Type '() => { baz: string; }' is not assignable to type '() => { status: string; }'.
    // Property 'status' is missing in type '{ bar: string; }' but required in type '{ status: string; }'.(2322)
    const foo: () => {status: string} = function () {
        return {
            // status: '200 OK'
            bar: 'baz',
        }
    }
    
    

    但是,在定义 函数类型

    const foo: () => {status: string} = function () {
        return {
            status: '200 OK',
            bar: 'baz', // No problem
        }
    }
    
    
    1. 为什么最后一个示例没有引发类型错误?
    2. 有没有办法使用 函数类型 ?

    See in playground

    1 回复  |  直到 4 年前
        1
  •  2
  •   T.J. Crowder    4 年前
    1. 为什么最后一个示例没有引发类型错误?

    因为 功能 {status: string, bar: string} ). 该返回类型实际上是变量所期望的函数的返回类型的子类,以确保赋值有效。

    1. 有没有办法使用函数类型对返回对象强制执行“无额外属性”?

    bar . TypeScript将从函数中推断变量的类型。

    playground link ):

    const foo2: () => {status: string} = function (): ReturnType<typeof foo2> {
        return {
            status: '200 OK',
            bar: 'baz',
        };
    };