by Deepu K Sasidharan

通过Deepu K Sasidharan

使用TypeScript映射和条件类型使React组件更出色 (Make your React components great with TypeScript mapped and conditional types)

You’ve probably heard about TypeScript. You may have heard someone claiming how great type safety is.

您可能听说过TypeScript。 您可能听说过有人声称这种类型的安全性非常好。

TypeScript is great. As someone who hates transpiling his code, I would definitely do it with TypeScript if I had to. So much has been said about TypeScript, and there isn’t really anything new that I can add. But I do believe that type safety is not all about making your code ugly with type definitions everywhere. So how can we write type-safe code without having to litter type declarations everywhere?

TypeScript很棒。 作为讨厌编译他的代码的人,如果需要的话,我一定会使用TypeScript做到这一点。 关于TypeScript的讨论已经很多了,实际上我没有什么可以添加的。 但是我确实相信类型安全并不仅仅在于使代码随处可见都是丑陋的。 那么,我们如何编写类型安全的代码而不必到处乱扔类型声明?

Type inference and advanced features like derived and dynamic types are the answer. Editors and IDEs we use are smart enough to handle code with inferred type gracefully without us having to see the types all the time visually. (Of course, they all usually show you the type when you hover over an inferred type.)

答案就是类型推断和高级功能,例如派生类型和动态类型。 我们使用的编辑器和IDE足够聪明,可以优雅地处理带有推断类型的代码,而无需我们一直在视觉上看到类型。 (当然,当您将鼠标悬停在推断的类型上时,它们通常都会向您显示类型。)

TypeScript has a very good type inference. As a rule of thumb, you can always start without declaring the type for any variable and see if the compiler infers it. With modern editors like VSCode, you can see this immediately. So set your tsconfig to the strict mode. Then start declaring types when the compiler complains.

TypeScript具有非常好的类型推断。 根据经验,您始终可以在不声明任何变量类型的情况下开始,并查看编译器是否推断出它。 使用像VSCode这样的现代编辑器,您可以立即看到这一点。 因此,将tsconfig设置为严格模式。 然后在编译器抱怨时开始声明类型。

Additionally, TypeScript 2.1 and 2.8 introduced a bunch of cool lookup types. Now you can dynamically infer types using different techniques like Intersection types, Union types, Index types, mapped types and conditional types.

此外,TypeScript 2.1和2.8引入了许多很酷的查找类型。 现在,您可以使用不同的技术动态推断类型,例如交集类型,联合类型,索引类型,映射类型和条件类型。

索引类型 (Index types)

Index types enable us to check properties and types of an interface or type dynamically using the keyof T (index type query operator) and T[K](indexed access operator). Let's take the below interface for example.

索引类型使我们能够使用keyof T ( 索引类型查询运算符)T[K] ( 索引访问运算符 )动态检查接口的属性和类型或动态类型 。 让我们以下面的界面为例。

interface Person {name: string;age: number;address: string;sayHi: (msg: string) => string;
}

The keyof T operator gets a union type of all the key names of the type Tand hence keyof Person will give us 'name' | 'age' | 'address' | sayHi' as result.

keyof T操作员搭乘的联合类型的类型的所有键名的T ,因此keyof Person会给我们'name' | 'age' | 'address' | sayHi' 'name' | 'age' | 'address' | sayHi' 'name' | 'age' | 'address' | sayHi'

The T[K] operator gets the type for the provided key. Person['name']will result in string and Person[keyof Person] will result in string | number | ((msg: string) => string).

T[K]运算符获取所提供键的类型。 Person['name']将导致stringPerson[ keyof Person]将导致string | number | ((msg: string) => string) string | number | ((msg: string) => string) string | number | ((msg: string) => string)

映射类型 (Mapped types)

Let us see what mapped types are. Let us say we have the below interface for a Person.

让我们看看什么是映射类型。 假设我们有一个Person的以下界面。

interface Person {name: string;age: number;address: string;sayHi: (msg: string) => string;
}

Now in every project, it is almost always a common requirement to have variations of a certain interface. For example, let’s say we need a read-only version of the person as below.

现在,在每个项目中,拥有特定接口的变体几乎总是一个共同的要求。 例如,假设我们需要如下所示的人员只读版本。

interface ReadonlyPerson {readonly name: string;readonly age: number;readonly address: string;readonly sayHi: (msg: string) => string;
}

In this case, we would have to replicate the Person interface and we have to keep them in sync manually. This is where mapped types will come in handy, so let us use the builtin mapped type, Readonly, for this.

在这种情况下,我们将必须复制Person接口,并且必须手动使其保持同步。 这是映射类型将派上用场的地方,因此让我们使用内置的映射类型Readonly

type ReadonlyPerson  = Readonly<Person>

If you hover over the ReadonlyPerson type you can see the inferred type as below.

如果将鼠标悬停在ReadonlyPerson类型上,则可以看到以下推断的类型。

That is cool, right? Now we can create types from existing types and don’t have to worry about keeping them in sync. How does it work, what does Readonly<Person> do? Let’s take a look at the mapped type.

太酷了吧? 现在,我们可以从现有类型创建类型,而不必担心保持它们同步。 它是如何工作的, Readonly<Person>什么作用? 让我们看一下映射类型。

type Readonly<T> = {readonly [K in keyof T]: T[K];
}

The in operator from TypeScript does the trick here. It maps all the declarations of the existing type into the new type. The keyof operator provides the keys from our type for the mapping. Let us build our own mapped type.

TypeScript的in运算符在这里起到了作用。 它将现有类型的所有声明映射为新类型。 keyof运算符提供了我们类型的映射键。 让我们建立自己的映射类型。

Let us say we need a read-only Person interface where all the fields are nullable as well. We can build a mapped type as below for that.

假设我们需要一个只读的Person接口,其中的所有字段也是可空的。 我们可以为此构建一个映射类型,如下所示。

type ReadonlyNullablePerson = {readonly [P in keyof Person]: Person[P] | null;
}

Let’s make it generic so that it can be used with any interface.

让我们使其通用,以便可以与任何接口一起使用。

type ReadonlyNullable<T> = {readonly [K in keyof T]: T[K] | null;
}type ReadonlyNullablePerson  = ReadonlyNullable<Person>

TypeScript includes Readonly<T>, Partial<T>, Pick<T, K extends keyof T> and Record<K extends string, T> as built-in mapped types. Pick and Record can be used as below, check them in your editor to see what types they produce.

TypeScript包括Readonly<T>Partial<T>Pick<T, K extends keyof T>Record<K extends string, T>作为内置映射类型。 选择和记录可按以下方式使用,请在编辑器中检查它们,以查看它们产生什么类型。

type PersonMinimal = Pick<Person, 'name' | 'age'>type RecordedPerson = Record<'name' | 'address', string>

For every other use case, you can build your own mapped types.

对于其他所有用例,您都可以构建自己的映射类型。

条件类型 (Conditional types)

A conditional type selects one of two possible types based on a condition expressed as a type relationship test.

条件类型根据表示为类型关系测试的条件选择两种可能的类型之一。

Let us look at an example.

让我们来看一个例子。

type Foo<T, U> = T extends U ? string : booleaninterface Me {}
interface You extends Person {}type FooBool = Foo<Me, Person> // will result in boolean
type FooString = Foo<You, Person> // will result in string

The type dynamically inferred from Foo<T, U> will be either string or boolean depending on what the first generic is extended from.

Foo<T, U>动态推断出的类型将是string还是boolean具体取决于第一个泛型的扩展名。

Let us see how we can mix conditional types with mapped types to infer a new type from Person which only includes the non-function properties.

让我们看看如何将条件类型与映射类型混合使用,以从Person推断出仅包含非函数属性的新类型。

type NonFunctionPropNames<T> = {[K in keyof T]: T[K] extends Function ? never : K
}[keyof T];type NonFunctionProps<T> = Pick<T, NonFunctionPropNames<T>>type PersonProps = NonFunctionProps<Person>// Produces the below type
// type PersonProps = {
//     name: string;
//     age: number;
//     address: string;
// }

We first get all the non-function property names from the interface. Then use the Pick mapped type to pick those from the interface to form the new interface.

我们首先从接口获取所有非功能属性名称。 然后使用“ 拾取”映射类型从接口中选择那些类型以形成新接口。

TypeScript provides following inbuilt conditional types:

TypeScript提供以下内置条件类型:

  • Exclude<T, U> – Exclude from T those types that are assignable to U.

    Exclude<T, U> –从T排除可分配给U那些类型。

  • Extract<T, U> – Extract from T those types that are assignable to U.

    Extract<T, U> –从T提取可分配给U那些类型。

  • NonNullable<T> – Exclude null and undefined from T.

    NonNullable<T> –从T排除nullundefined

  • ReturnType<T> – Obtain the return type of a function type.

    ReturnType<T> –获取函数类型的返回类型。

  • InstanceType<T> – Obtain the instance type of a constructor function type.

    InstanceType<T> –获取构造函数类型的实例类型。

让我们使用它 (Let us put it into use)

These advanced types become even more powerful when you combine them together. Let’s see some practical uses of this in React.

当您将它们组合在一起时,这些高级类型将变得更加强大。 让我们看看这在React中的一些实际用法。

ES6中的React组件和Redux Reducer (React component and Redux reducer in ES6)

Let see a simple React component with a reducer written in ES6. Take a look at index.jsx in the below code sandbox:

让我们看一个简单的带有ES6编写的带有reducer的React组件。 在下面的代码沙箱中查看index.jsx

As you can see, we use the prop-types library to define the component props. It is not the most efficient way, as it includes considerable overhead during development. It doesn’t provide full type safety anyway.

如您所见,我们使用prop-types库定义组件prop。 这不是最有效的方法,因为它在开发过程中会包含大量开销。 无论如何,它不提供全类型的安全性。

在TypeScript中使用React组件和Redux reducer (React component and Redux reducer in TypeScript)

Now let us convert this simple example to TypeScript so that it's type safe. Take a look at index.tsx in the below code sandbox:

现在,让我们将这个简单的示例转换为TypeScript,以确保其类型安全。 在下面的代码沙箱中查看index.tsx

As you can see, the code is more type-safe now. It is also much more verbose even without PropTypes library and all the type inference.

如您所见,该代码现在更加类型安全。 即使没有PropTypes库和所有类型推断,它也更加冗长。

使用高级类型在TypeScript中使用React组件和Redux reducer (React component and Redux reducer in TypeScript with advanced types)

Now let us apply the advanced types that we learned to make this example less verbose and even more type safe. Take a look at index.tsx in the below code sandbox:

现在,让我们应用我们学到的高级类型,使该示例不再冗长,甚至更加安全。 在下面的代码沙箱中查看index.tsx

As you can see, we used Readonly and ReturnType mapping along with some other type inference techniques to write a more type-safe but less verbose version of the component.

如您所见,我们使用ReadonlyReturnType映射以及其他一些类型推断技术来编写类型更安全但不那么冗长的组件版本。

结论 (Conclusion)

If you are using React with TypeScript, then these are some of the techniques you must apply. If you are considering a type system for React, then look no further than TypeScript. It has great features, great tooling, excellent IDE/Editor support and an awesome community.

如果您将React与TypeScript一起使用,那么这些是您必须应用的一些技术。 如果您正在考虑使用React的类型系统,那么TypeScript就是您的最佳选择。 它具有强大的功能,强大的工具,出色的IDE /编辑器支持以及强大的社区。

I gave a talk on TypeScript for Devoxx 2018, and you can see the video and slides if you like here.

我在Devoxx 2018的TypeScript上进行了演讲,如果您愿意的话可以观看视频和幻灯片。

Check out my book “Full Stack Development with JHipster” on Amazon and Packt if you like to learn about Full stack development with an awesome stack.

如果您想了解有关使用超赞堆栈进行全栈开发的知识,请查看我在Amazon和Packt上撰写的使用JHipster进行全栈开发 ”一书。

If you like JHipster don’t forget to give it a star on Github.

如果您喜欢JHipster,请不要忘记在Github上给它加个星。

If you like this article, please leave some claps (Did you know that you can clap multiple times? ? )

如果您喜欢本文,请留下一些鼓掌(您知道您可以多次鼓掌吗??)

You can follow me on Twitter and LinkedIn.

您可以在Twitter和LinkedIn上关注我。

翻译自: https://www.freecodecamp.org/news/make-react-components-great-again-with-typescript-mapped-and-conditional-types-fa729bfc1a79/

使用TypeScript映射和条件类型使React组件更出色相关推荐

  1. 如何有条件地向React组件添加属性?

    如果满足特定条件,是否有办法仅将属性添加到R​​eact组件? 我应该在渲染后基于ajax调用将required和readOnly属性添加到表单元素中,但是由于readOnly =" fal ...

  2. 为了使界面组件更圆滑,Swing,且跨系统

    转载于:https://www.cnblogs.com/chengbao/p/4858860.html

  3. TS中的条件类型(ReturnType)

    本偏介绍TS另一种高级类型-条件类型. 官方文档:https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distr ...

  4. 一文详解 React 组件类型

    本文的目标是让开发者清晰地了解 React 组件类型,哪些在现代 React 应用中依然在使用,以及为何一些类型现在不再使用了. 作者 | Robin Wieruch 译者 | 弯月 责编 | 屠敏 ...

  5. react组件深度解读

    五.React 核心是组件 在 React 中,我们使用组件(有状态.可组合.可重用)来描述 UI . 在任何编程语言中,你都可以将组件视为简单的函数. React 组件也一样, 它的输入是 prop ...

  6. react 组件引用组件_动画化React组件

    react 组件引用组件 So, you want to take your React components to the next level? Implementing animations c ...

  7. TypeScript 2.8引入条件类型

    最新发布的TypeScript 2.8包含了若干主要特性和一些问题修复,其中最为重要的是新增了条件类型,开发人员可以根据其他类型的特征为变量选择适当的类型. 条件类型最适合与泛型组合在一起使用.如果一 ...

  8. 关于 typescript 里面的 分布式条件类型

    1. 什么是分布式条件类型 非分布式: 操作作用于混合类型大家都有的成员, 也就是交集 分布式: 操作应用于混合类型里所有的成员, 也就是并集 代码演示 // 非分布式(操作只作用于共同成员) typ ...

  9. React组件库实践:React + Typescript + Less + Rollup + Storybook

    背景 原先在做低代码平台的时候,刚好有搭载React组件库的需求,所以就搞了一套通用的React组件库模版.目前通过这套模板也搭建过好几个组件库. 为了让这个模板更干净和通用,我把所有和低代码相关的代 ...

最新文章

  1. 电阻存储器为edge-AI提供了仿生架构
  2. MATLAB 图像的傅里叶变换
  3. Spring注解——使用@ComponentScan自动扫描组件
  4. python实现字母的加密和解密 字典_python实现AES加密与解密
  5. eclipse 3.7 search 报resource is out of sync with the file system 解决方法
  6. 常见问题与常见算法的时间复杂度
  7. itsdangerous
  8. Windows中的NTUSER.DAT文件是什么?
  9. 2020年中国天线行业发展现状及细分市场结构分析[图]
  10. Kali系统安装Visual Studio Code
  11. 12个可以免费自学编程的网站
  12. c++读取stl文件
  13. 原来我们都让历史书骗了- -#!~
  14. 主体阶段钢筋工程、模板工程、混凝土、管线预埋施工要点都有哪些?
  15. AE/PR模板:10组电影质感海报宣传文字标题设计动画Cinematic Titles
  16. 全系列计算机等级考试题库软件+Office2016
  17. 在计算机软件中怎么拍照,计算机相机相机软件,这三个软件不仅用于拍照
  18. 【dojo】dojo.ready(dojo.addOnLoad) “前传”
  19. Chrome离线安装插件
  20. 使用交叉编译工具链编译并调试linux内核

热门文章

  1. 1小时学会:最简单的iOS直播推流(十)librtmp使用介绍
  2. iOS arm 64 的了解
  3. IOS 自定义相机, 使用 AVFoundation(附实现部分腾讯水印相机功能 demo)
  4. JavaScript 事件冒泡简介及应用(转)
  5. VUE中使用Echarts绘制地图迁移
  6. 洛谷 P1598 垂直柱状图【字符串+模拟】
  7. 大数据、智慧城市成生态贵州新名片
  8. 自定义UISearchBar外观
  9. centos iptables关于ping
  10. Sco Unixware 7.1.3企业版服务器安装视频教程