简体   繁体   English

请解释这个涉及 generics 和类型别名的 typescript 语法

[英]Please explain this typescript syntax involving generics and type alias

I am trying to follow some tutorials and i have difficulties in understanding typescript syntax.我正在尝试学习一些教程,但在理解 typescript 语法时遇到了困难。 Kindly provide an explanation to the following typescript syntax请提供对以下 typescript 语法的解释

1 1

type ValidationResult<T, U> = Partial<{ [Key in keyof T]: U }>;

I could not find an example in the generics chapter in typescript handbook that describes something like <T, U> part of the above statement - what does it mean?我在 typescript 手册的 generics 章节中找不到一个示例,该示例描述了上述语句的<T, U>部分之类的内容-这是什么意思? does it mean T is input and U is output?这是否意味着输入TU是 output?

I understand Partial but can't seem to understand Partial<{ [Key in keyof T]: U }> please explain what it means我理解 Partial 但似乎无法理解Partial<{ [Key in keyof T]: U }>请解释一下这是什么意思

2 2

type Validation<T, U> = (fields: T) => ValidationResult<T, U>; 

Does the above statement define a type alias for a function that accepts a type T and returns a ValidationResult<T, U> ?上述语句是否为接受类型T并返回ValidationResult<T, U>的 function 定义了类型别名?

What does the U represent? U代表什么?

3 3

const hasLength = <T>(len: number, input: string | Array<T>) =>
input.length >= len;

const hasUserName = (input: string) =>
hasLength(1, input) ? true : "Name is required.";

What does <T>(len: number, input: string | Array<T>) represent? <T>(len: number, input: string | Array<T>)代表什么?

what does the leading <T> mean in the above declaration?上述声明中的前导<T>是什么意思?

Can you explain what the above two declarations mean?你能解释一下上述两个声明的含义吗?

What is the relationship between the above two declarations const hasLength and const hasUserName ?上面两个声明const hasLengthconst hasUserName是什么关系?

4 4

const fieldValues = {
    name: "Test User",
    level: 10,
    description: "Test Description"
};

type FieldValues = typeof fieldValues;

const validationRules = [
    ({ name }: FieldValues) => ({
        name: hasUserName(name)
    }),
    ({ description }: FieldValues) => ({
        description: hasValidDescription(description)
    })
];

I understand const fieldValues is assigned with an object literal and hence fieldValues value will be我了解const fieldValues分配有 object 文字,因此fieldValues值将是

{
    name: "Test User",
    level: 10,
    description: "Test Description"
}

Now, what does the line type FieldValues = typeof fieldValues;现在,行type FieldValues = typeof fieldValues;是什么? mean?意思是?

What is the significance of using typeof in the above declaration?在上面的声明中使用typeof有什么意义呢?

Also explain the block of code that follows that statement还要解释该语句后面的代码块

TIA!蒂亚!

For starters, "generics" are also called "parametric polymorphism" and the first type parameter is often called 'T' (for Type), any additional parameter is just the alphabetically next character (T, U, V...).对于初学者,“泛型”也称为“参数多态性”,第一个类型参数通常称为“T”(用于 Type),任何附加参数只是按字母顺序排列的下一个字符(T、U、V...)。

1) Partial Types 1) 部分类型

Partial Types allow you to construct a new type, with all the properties of T, but they are optional and can be missing. 部分类型允许您构造一个新类型,具有 T 的所有属性,但它们是可选的并且可能会丢失。

type ValidationResult<T, U> = Partial<{ [Key in keyof T]: U }>;

This means, "I create a type from T with all the properties of type U".这意味着,“我从 T 创建了一个具有类型 U 的所有属性的类型”。 For example ValidationResult<MyType, string> would contain all string properties from 'MyType'.例如ValidationResult<MyType, string>将包含来自“MyType”的所有字符串属性。

Note: the [name-expression]: type is called 'computed property'.注意: [name-expression]: type称为“计算属性”。

interface Test{
    foo: string,
    bar: number
}

type ValidationResult<T, U> = Partial<{ [Key in keyof T]: U }>;

let v: Baz<Test, string> = { foo: 't', bar: 1 }; // Error! bar is not a string!

2) Function type 2) Function 型

type Validation<T, U> = (fields: T) => ValidationResult<T, U>; 

'Validation' is a function type that takes some type T and returns a partial type that contains all the properties from T that have type U. “验证”是一个 function 类型,它采用某种类型 T 并返回一个部分类型,该类型包含 T 中具有类型 U 的所有属性。

So the return type is what we defined before, but this function just gives us one of these ValidationResults.所以返回类型就是我们之前定义的,但是这个 function 只是给了我们这些 ValidationResults 之一。

3) Union types and anonymous functions 3) 联合类型和匿名函数

const hasLength = <T>(len: number, input: string | Array<T>) =>
input.length >= len;

So this is an anonymous function (or "lambda"):所以这是一个匿名的 function(或“lambda”):

(len: number, input:string) => input.length >= len

This is a function from (number, string) to boolean.这是从(数字,字符串)到 boolean 的 function。 The <T> is a type parameter, so it's a generic lambda! <T>是一个类型参数,所以它是一个通用的 lambda!

<T>(n: number, T: x) => doSomething...

A type of the form string | number | T一种形式的string | number | T string | number | T string | number | T is a union type , ie, it may take any value allowed in each of the listed types: 'abc' or 123 or whatever T is... string | number | T是一个联合类型,即它可以采用每个列出的类型中允许的任何值:'abc' 或 123 或任何 T 是...

So 'hasLength' is a (lambda) function that compares 'len' to the length of the string or Array of Ts argument.所以'hasLength'是一个(lambda)function,它将'len'与Ts参数的字符串或数组的长度进行比较。

const hasUserName = (input: string) =>
hasLength(1, input) ? true : "Name is required.";

This just uses the above function and passes a string as argument.这只是使用上面的 function 并将字符串作为参数传递。 You could also call:您也可以致电:

hasLength(1, ['a', 'b'])

That is 'hasLength of number, Array'.那是'hasLength of number,Array'。

4) Anonymous types 4) 匿名类型

So like you said, we assign an object literal to our constant.所以就像你说的,我们为我们的常量分配了一个 object 文字。 But what's the type of the constant?但是常量的类型是什么? The most general would probably be 'object', but that's not useful at all!最通用的可能是“对象”,但这根本没有用!

The 'typeof' operator gives us the type of our object. “typeof”运算符为我们提供了 object 的类型。 Even though we have never defined an interface or a class and we haven't given a name to this object, we have gotten it's (unnamed) type into the variable 'FieldValues'.即使我们从未定义过接口或 class 并且我们没有给这个 object 命名,我们已经将它的(未命名)类型放入变量“FieldValues”中。 Then we can use that type:然后我们可以使用该类型:

const validationRules = [
    ({ name }: FieldValues) => ({
        name: hasUserName(name)
    }),
    ({ description }: FieldValues) => ({
        description: hasValidDescription(description)
    })
];

This is an array (see the [] ) containing functions.这是一个包含函数的数组(参见[] )。 The function uses an admittedly strange syntax to say, that it takes an object named 'name' of type 'FieldValues' and it returns an object. function 使用一种公认的奇怪语法来表示,它需要一个名为“name”的“FieldValues”类型的 object,它返回一个 object。

1 1

type ValidationResult<T, U> = Partial<{ [Key in keyof T]: U }>;

In this example U is a generic - so it represents any type.在这个例子中U是一个泛型 - 所以它代表任何类型。 You define these generics when you use the type:使用类型时定义这些 generics:

type ValidationResult<T, U> = Partial<{ [Key in keyof T]: U }>;

type TestType = {
    a: string,
    b: number,
};

const x: ValidationResult<TestType, string> = {
    a: 'test1',
    b: 'test2',
};

const y: ValidationResult<TestType, string> = {
    a: 'test1',
    // @ts-expect-error
    c: 'test3',
};

Playground Link. 游乐场链接。 So the type ValidationResult defines a type which will have any number of keys from type T , and those keys will have values of type U , whatever that is defined as.因此类型ValidationResult定义了一个类型,该类型将具有来自类型T的任意数量的键,并且这些键将具有类型U的值,无论定义为什么。

2 2

type Validation<T, U> = (fields: T) => ValidationResult<T, U>;

You are right;你说的对; Validation is a type of function, which takes some value of type T , and returns a ValidationResult<T, U> ; Validation是 function 的一个类型,它接受一些T类型的值,并返回一个ValidationResult<T, U> U in this example is defined as above, when the type is used:本例中的U定义如上,当使用类型时:

type ValidationResult<T, U> = Partial<{ [Key in keyof T]: U }>;

type TestType = {
    a: string,
    b: number,
};

type Validation<T, U> = (fields: T) => ValidationResult<T, U>;

const f1: Validation<TestType, number> = fields => ({ a: 2, b: 3 });
// @ts-expect-error
const f2: Validation<TestType, number> = fields => ({ c: 4 });

Playground link. 游乐场链接。

3 3

const hasLength = <T>(len: number, input: string | Array<T>) =>
    input.length >= len;

const hasUserName = (input: string) =>
    hasLength(1, input) ? true : "Name is required.";

<T>(len: number, input: string | Array<T>) is defining the arguments of the function: 1. len is a number 2. input is a union type of string and Array<T> ; <T>(len: number, input: string | Array<T>)定义了 function 的 arguments: 1. len是一个数字 2. inputstringArray<T>的联合类型; meaning, it's either a string or an array of some type T ;意思是,它要么是字符串,要么是某种类型的数组T both of these types have a length property which can be used.这两种类型都有一个可以使用的length属性。

The leading T is a generic;前导T是泛型; it represents some type;它代表某种类型; we're just saying that we don't want to define what that type is in the function, it could be anything.我们只是说我们不想在 function 中定义该类型是什么,它可以是任何东西。

The relationship between hasLength and hasUserName is that the latter uses the former to check whether the username is at least one chatacter. hasLengthhasUserName的关系是后者使用前者来检查用户名是否至少是一个字符。 Typescript can know that when hasUserName calls hasLength with input as the second argument, T in hasLength will be a string. Typescript 可以知道,当hasUserNameinput作为第二个参数调用hasLength时, hasLength中的T将是一个字符串。

4 4

const fieldValues = {
    name: "Test User",
    level: 10,
    description: "Test Description"
};

type FieldValues = typeof fieldValues;

const validationRules = [
    ({ name }: FieldValues) => ({
        name: hasUserName(name)
    }),
    ({ description }: FieldValues) => ({
        description: hasValidDescription(description)
    })
];

typeof is a typescript keyword that takes the type of a value. typeof是一个 typescript 关键字,它采用值的类型。 So FieldValues is actually a type which would look like:所以FieldValues实际上是一个看起来像这样的类型:

type FieldValues = {
    name: string;
    level: number;
    description: string;
};

The next block of code defines an array of functions which take in a FieldValues object, and return an object.下一个代码块定义了一个函数数组,这些函数接受一个FieldValues object,并返回一个 object。 The key on the object indicates whether the fieldValues object is valid for some property. object 上的键表示字段Values fieldValues是否对某些属性有效。 I'm guessing they use this to validate a number of fields.我猜他们用它来验证一些字段。

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

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