首页 > 其他分享 >[Typescript] Handling conditional return type of a function

[Typescript] Handling conditional return type of a function

时间:2023-01-27 19:55:05浏览次数:47  
标签:function Typescript return greeting goodbye type hello

import { expect, it } from "vitest";
import { Equal, Expect } from "../helpers/type-utils";

function youSayGoodbyeISayHello(greeting: unknown) {
  return greeting === "goodbye" ? "hello" : "goodbye";
}

it("Should return goodbye when hello is passed in", () => {
  const result = youSayGoodbyeISayHello("hello");

  type test = [Expect<Equal<typeof result, "goodbye">>];

  expect(result).toEqual("goodbye");
});

it("Should return hello when goodbye is passed in", () => {
  const result = youSayGoodbyeISayHello("goodbye");

  type test = [Expect<Equal<typeof result, "hello">>];

  expect(result).toEqual("hello");
});

So in the function `youSayGoodbyISayHello`, we want both runtime and compile time type safety. The the return type of the function should either be `hello` or `goodbye` based on the input params is `goodbye` or `hello`.

 

Solution 1: using () as any

function youSayGoodbyeISayHello<T extends 'goodbye' | 'hello'>(
  greeting: T
): T extends 'goodbye' ? 'hello' : 'goodbye' {
  return (greeting === 'goodbye' ? 'hello' : 'goodbye') as any;
}

The idea is typescript is not smart enough to know greeting === 'goodbye' ? 'hello' : 'goodbyethe return type is string `goodbye` or `hello`, therefore you need to use as anyjust let typescript know, you know exactly what return type it is.

 

Solution 2: as GreetingReturnType<T>

type GreetingReturnType<T extends 'goodbye' | 'hello'> = T extends 'goodbye'
  ? 'hello'
  : 'goodbye';

function youSayGoodbyeISayHello<T extends 'goodbye' | 'hello'>(greeting: T) {
  return (
    greeting === 'goodbye' ? 'hello' : 'goodbye'
  ) as GreetingReturnType<T>;
}

 

标签:function,Typescript,return,greeting,goodbye,type,hello
From: https://www.cnblogs.com/Answer1215/p/17069251.html

相关文章

  • Functions, Equations and Polynomials (Pure Math)
    MO题乱做\(f:\mathbb{N}^*\mapsto\mathbb{N}^*,\foralln\in\mathbb{N}^*,f(f(n))<f(n+1)\).求\(f(n)\).有一个很厉害的做法.首先我们证明\(f(1)\)是\(\{f(k)|......
  • TypeScript readonly props All In One
    TypeScriptreadonlypropsAllInOneTS绕过readonly限制readonlypropertiesinterfacePerson{name:string;age:number;}interfaceReadonlyPerson{......
  • 【个人笔记】2023年搭建基于webpack5与typescript的react项目
    写在前面由于我在另外的一些文章所讨论或分析的内容可能基于一个已经初始化好的项目,为了避免每一个文章都重复的描述如何搭建项目,我在本文会统一记录下来,今后相关的文章直......
  • TypeScript reuse object's props All In One
    TypeScriptreuseobject'spropsAllInOneexport{};constlog=console.log;//typeCSSProps={[prop:string]:CSSProps};//typeCSSProps=CSSProps[]......
  • Functions
    BacktoDefinitionsfunction - anamedsequenceofstatementsthatperformsaspecifictaskorusefuloperationparameter - avariablethatreceivesanar......
  • Variables, Built-in Functions
    SomeDefinitionsWelearnedhowtoproducevaluesfromusingoperatorsonothervalues.Wecreatedexpressions!.expression-afragmentofcodethatproduces......
  • 小程序逆向错误之 typeof3 is not a function
    反编译小程序的解包,在微信开发者工具当中预览界面是空白的。Console显示 app.js错误:TypeError:_typeof3isnotafunction 按错误提示找到文件@babel/runtime/hel......
  • TypeScript Generic & Arrow Function All In One
    TypeScriptGeneric&ArrowFunctionAllInOne(......
  • 关于typescript异构枚举实现解析
    这里有几种实现方式:第一种是:A,B的实现Enum[Enum["A"]=0]="A";x=Enum["A"]=0;//x的值为0也就是说:Enum有两个键值:一个是0,他的值是“A”;一个是“A”,他的值是0;Enum......
  • typescript联合类型的类型缩减使用
    never是所有类型的子类型当我们想要一个这样一个类型时困难1因为采用索引签名要满足所有成员都必须符合字符串的索引签名所有不能采用{[index:string]:string|ag......