繁体   English   中英

通用 function 的返回类型不可分配给实际返回类型

[英]Return type of generic function not assignable to actual return type

不知道如何使类型工作。 我正在约束t并且返回的值是正确的,但是 typescript 似乎无法解决这个问题。


interface Foo {
  a: number
  b: string
}

function f <T extends keyof Foo>(t: T): Foo[T] | undefined {
  if (t === 'a') {
    return 1 + 4 // ⚠️ error here
  }
  return
}

const a1 = f('a') // should be number | undefined return type
const b1 = f('b') // should be string | undefined return type


Type 'number' is not assignable to type 'Foo[T] | undefined'

解决方法,呃

function f <T extends keyof Foo>(t: T): Foo[T] | undefined {
  if (t === 'a') {
    return 1 + 4 as Foo[T]
  }
  return
}

将 Foo[T] 替换为 Foo[keyof Foo]。 它对我有用。

interface Foo {
  a: number
  b: string
};

const a = <T extends keyof Foo>(t: T): Foo[keyof Foo] | undefined => {
  if (t === 'a') {
    return 1 + 4
  };
  
  return
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM