TypeScript类型级别和值级别如何区分

发布时间:2023-02-27 14:30:32 作者:iii
来源:亿速云 阅读:109

这篇文章主要介绍“TypeScript类型级别和值级别如何区分”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“TypeScript类型级别和值级别如何区分”文章能帮助大家解决问题。

对值级别编程类型级别编程区分

首先,让我们对值级别编程和类型级别编程进行重要区分。

JavaScript没有类型,所以所有JavaScript都是值级别的代码:

// A simple Javascript function:
function sum(a, b) {
  return a + b;
}

TypeScript允许我们将类型注释添加到JavaScript中,并确保我们编写的sum函数永远不会用数字以外的任何东西调用:

// Using type annotations:
function sum(a: number, b: number): number {
  return a + b;
}

但TypeScript的类型系统远比这强大得多。我们编写的真实代码有时需要是通用的,并接受我们事先不知道的类型。

在这种情况下,我们可以在尖括号<A,B,&hellip;>中定义类型参数然后,我们可以将类型参数传递给一个类型级函数,该函数根据输入类型计算输出类型:

// Using type level programming:
function genericFunction<A, B>(a: A, b: B): DoSomething<A, B> {
  return doSomething(a, b);
}

这就是类型级编程!DoSomething<A,B> 是一种用特殊编程语言编写的类型级函数,它与我们用于值的语言不同,但同样强大。让我们将这种语言称为类型级TypeScript。

// This is a type-level function:
type DoSomething<A, B> = ...
// This is a value-level function:
const doSomething = (a, b) => ...

类型级编程

类型级TypeScript是一种最小的纯函数语言。

在类型级别,函数被称为泛型类型:它们接受一个或多个类型参数并返回单个输出类型。下面是一个函数的简单示例,该函数使用两个类型参数并将它们包装在元组中:

type SomeFunction<A, B> = [A, B];
/*                ----    ------
                   ^         \
                  type        return type
               parameters
     \-------------------------/
                 ^
              Generic
*/

类型级别的TypeScript没有很多功能。毕竟,它是专门为你的代码做类型约束的!也就是说,它确实有足够的特性(几乎)图灵完备,这意味着你可以用它解决任意复杂的问题。

这是我们将在接下来的章节中学习的语言类型的简要概述。现在,让我们开始第一次挑战吧!

挑战是如何工作的

在每一章结束时,你将有一些挑战需要解决,以将你的新技能付诸实践。它们看起来像这样:

namespace challenge {
  // 1. implement a generic to get the union
  // of all keys in an object type.
  type GetAllKeys<Obj> = TODO;
  type res1 = GetAllKeys<{ a: number }>;
  type test1 = Expect<Equal<res1, "a">>;
}

在此之前你要先定义好Expect和Equal

type Expect<T extends true> = T;
type Equal<X, Y> = (<T>() => T extends { [k in keyof X]: X[k]; } ? 1 : 2) extends <T>() => T extends { [k in keyof Y]: Y[k]; } ? 1 : 2 ? true : false;

挑战

准备好迎接你的第一个挑战了吗?出发:

/**
 * 1. The `identity` function takes a value of any type
 *    and returns it. Make it generic!
 */
namespace genericFunction {
  function identity(a: TODO): TODO {
    return a;
  }
  let input1 = 10;
  let res1 = identity(input1);
  type test1 = Expect<Equal<typeof res1, number>>;
  let input2 = "Hello";
  let res2 = identity(input2);
  type test2 = Expect<Equal<typeof res2, string>>;
}
/**
 * 2. `safeHead` takes an array, a default value
      and returns the first element of the array
      if it isn't empty. Make it generic!
 */
namespace safeHead {
  function safeHead(array: TODO[], defaultValue: TODO): TODO {
    return array[0] ?? defaultValue;
  }
  let input1 = [1, 2, 3];
  let res1 = safeHead(input1, 0);
  type test1 = Expect<Equal<typeof res1, number>>;
  let input2 = ["Hello", "Hola", "Bonjour"];
  let res2 = safeHead(input2, "Hi");
  type test2 = Expect<Equal<typeof res2, string>>;
}
/**
 * 3. `map` transforms all values in an array to a value of
 *    different type. Make it generic!
 */
namespace map {
  function map(array: TODO[], fn: (value: TODO) => TODO): TODO[] {
    return array.map(fn);
  }
  let input1 = [1, 2, 3];
  let res1 = map(input1, value => value.toString());
  type test1 = Expect<Equal<typeof res1, string[]>>;
  let input2 = ["Hello", "Hola", "Bonjour"];
  let res2 = map(input2, str => str.length);
  type test2 = Expect<Equal<typeof res2, number[]>>;
}
/**
 * 4. `pipe2` takes a value and pipes it into 2 functions
 *    sequentially. For example, `pipe2(x, f1, f2)` will
 *    result in `f2(f1(x))`. Make it generic!
 *    
 */
namespace pipe2 {
  function pipe2(
    x: TODO,
    f1: (value: TODO) => TODO,
    f2: (value: TODO) => TODO
  ): TODO {
    return f2(f1(x));
  }
  let res1 = pipe2(
    [1, 2, 3],
    arr => arr.length,
    length => `length: ${length}`
  );
  type test1 = Expect<Equal<typeof res1, string>>;
  let res2 = pipe2(
    { name: 'Alice' },
    user => user.name,
    name => name.length > 5
  );
  type test2 = Expect<Equal<typeof res2, boolean>>;
}

关于“TypeScript类型级别和值级别如何区分”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

推荐阅读:
  1. Typescript和Javascript的区别是什么
  2. TypeScript中引用资源文件后提示找不到怎么办

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

typescript

上一篇:Java如何使用junit框架进行代码测试

下一篇:mysql-connector-java与mysql版本的对应关系是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》