【问题标题】:Typescript does not infer parsed attributes from a flat attributes functionTypescript 不会从平面属性函数中推断出解析的属性
【发布时间】:2020-04-04 05:56:08
【问题描述】:

我有一个函数负责扁平化对象属性。

async function query<T = {}>(query: string): Promise<T> {
  return Promise.resolve({
    value: 'random value here',
    randomAttribute: 'randomValue'
  }) as any
}

type QueryResult<T> = {
  id: string
  data: T
}

async function runSomeQuery() {
  const result = await query<QueryResult<{ name: string, age: string }>>('SELECT SOMETHING FROM ANOTHER THING')
  const parsedResult = flatResult(result)
  return parsedResult.name
}

function flatResult<T extends QueryResult<{}>>(queryResult: T) {
  return {
    id: queryResult.id,
    ...queryResult.data
  }
}

但是flatResult() 推断的返回类型缺少名称和年龄属性,所以当我尝试执行parsedResult.name 时出现错误。

游乐场链接:https://www.typescriptlang.org/play/?ssl=24&ssc=2&pln=1&pc=1#code/IYZwngdgxgBAZgV2gFwJYHsIwI4IKYBOYAPACowC8MA3gL4B8AFLoWAFwwjIGoQDmASg4AFAugC2qEHjL0aAKBgwCeZAgJZREqXgB0KkOgA2ANzyNqipTBPAj+DgHICwCABMJNu-hgALQniOADRWSi7uEgCCyNyoAEYIyHhO4R7iAGregVa0AjCg+RBg8rTy8shgAA54MACK+EQASnggCEbIspQKSqhuHFw8-FZuwMjAHKQlZaCQsIgoGFgESADKEnj1rIx5lkpQmFzKLW3IXcAA7sCopyxExJtNx+3E1DAQwOLJnLH8Qfl8XwGvD4MAYTEcKwAogAZSEAYXIKwA8gBZSGkAASAEkAHIAcRgADFGqiYJEcUjMZDGjBMbi8Y4BFZ9hBDpVgARpG5mq12l04EZRjyTowDCcmWFVOosOzOXhuU9kLp3p8pvJ5lA0Jh4ILkMLnuQ8AAPJLuEB1BpgfUdOj0Ji3K2KiY7KwqNQabrWXocB3W3S9ELWGC6EO+xW6EZjHIlIA

那么,我应该怎么做才能让这个推断正确?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以简单地依赖 TypeScript 泛型中的类型参数干扰:即让传递给 flatResult() 的参数确定返回类型:

    function flatResult<T>(queryResult: QueryResult<T>) {
      return {
        id: queryResult.id,
        ...queryResult.data
      }
    }
    

    之所以如此,是因为编译器会查看参数queryResult 的类型。当您在此行中调用/调用flatResult 时:

    // In the line below, `result` has the correct inferred type
    const result = await query<QueryResult<{ name: string, age: string }>>('SELECT SOMETHING FROM ANOTHER THING')
    
    // And this type will be passed into `flatResult()` and available to the generic type
    const parsedResult = flatResult(result)
    

    您实际上已经通知flatResult result 的类型应该是任何类型,键入为QueryResult&lt;{ name: string, age: string }&gt;

    See proof-of-concept example on TypeScript Playground.

    【讨论】:

    • 非常感谢您。我认为当你定义一个泛型类型时,你必须在函数调用中明确定义它,比如 flatResult.
    • @BrunoQuaresma 没问题!非常乐意提供帮助。这实际上也是我几天前在处理推断类型时学到的新东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多