【问题标题】:Typescript enforcing function return types based on template variable基于模板变量的打字稿强制函数返回类型
【发布时间】:2021-08-15 15:56:17
【问题描述】:

在 Typescript 中,您可以重载函数,以便根据输入参数具有不同的返回类型:

function test2(b: true): {a: number};
function test2(b: false): {x: number};
function test2(b: boolean): {a: number} | {x: number} {
  if(b) return {a: 1};

  return {x: 1};
}

const a_t2: {a: number} = test2(true);
const x_t2: {x: number} = test2(false);

我正在寻找一种在函数本身内隐式强制执行返回类型的方法。如果你写这个函数体,Typescript 不会抛出错误:

function test2(b: true): {a: number};
function test2(b: false): {x: number};
function test2(b: boolean): {a: number} | {x: number} {
  // breaking the contract 
  if(b === false) return {a: 1};

  return {x: 1};
}

我得到的最接近有效解决方案的是这个例子,虽然它会引发一些错误:


function test<B extends boolean>(b: B): B extends true ? {a: number} : {x: number} {
  if(b) {
    // Type '{ a: number; }' is not assignable to type 'B extends true ? { a: number; } : { x: number; }'.(2322)
    return {a: 1};
  } else {
    // Type '{ x: number; }' is not assignable to type 'B extends true ? { a: number; } : { x: number; }'.(2322)
    return {x: 2};
  }
}

const a_t = test(true);  // {a: number}
const x_t = test(false); // {b: number}

我可以通过将返回值转换为:

  if(b) {
    return {a: 1} as B extends true ? {a: number} : never;
  } else {
    return {x: 2} as B extends true ? never : {x: number};
  }

但它违背了对返回值进行隐式严格的目的。

有人知道更好的解决方案吗?

【问题讨论】:

  • 这能回答你的问题吗? Overloads not typechecking body
  • 谢谢,罗伯托。这是一个很好的答案,但它只谈论函数重载。我知道重载不会检查返回类型。我正在尝试使用模板对返回值进行类型检查来找到解决方案。虽然我不确定这是否可能
  • 查看stackoverflow.com/a/67712372/3388225。有一些解决方案。但通常你最好手动检查一下
  • 感谢@aleksxor 提供链接。我发现我要的是here, in this issue。从外观上看,我对这个不走运。我一直在寻找类型安全,以防有人(甚至是我)几年后更改函数体并且不注意实现或错过返回类型中可能的分支

标签: typescript function templates casting return


【解决方案1】:

感谢cmets,这里有类似的问题和答案stackoverflow.com/a/67712372/3388225

它很好地解释了为什么还不能做我在原始问题中提出的问题,并且有一个 Typescript Github 问题here 关于这个确切的事情。

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2019-08-04
    • 2021-05-16
    相关资源
    最近更新 更多