Utility types в typescript

Utility Types

TypeScript provides several utility types to facilitate common type transformations. These utilities are available globally.

This type is meant to model operations like await in async functions, or the .then() method on Promise s — specifically, the way that they recursively unwrap Promise s.

Constructs a type with all properties of Type set to optional. This utility will return a type that represents all subsets of a given type.

Constructs a type consisting of all properties of Type set to required. The opposite of Partial .

Constructs a type with all properties of Type set to readonly , meaning the properties of the constructed type cannot be reassigned.

This utility is useful for representing assignment expressions that will fail at runtime (i.e. when attempting to reassign properties of a frozen object).

ts
function freezeType>(obj: Type): ReadonlyType>;

Constructs an object type whose property keys are Keys and whose property values are Type . This utility can be used to map the properties of a type to another type.

Constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type .

Constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals). The opposite of Pick .

Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers .

Constructs a type by extracting from Type all union members that are assignable to Union .

Constructs a type by excluding null and undefined from Type .

Constructs a tuple type from the types used in the parameters of a function type Type .

Constructs a tuple or array type from the types of a constructor function type. It produces a tuple type with all the parameter types (or the type never if Type is not a function).

Constructs a type consisting of the return type of function Type .

Constructs a type consisting of the instance type of a constructor function in Type .

Extracts the type of the this parameter for a function type, or unknown if the function type has no this parameter.

Removes the this parameter from Type . If Type has no explicitly declared this parameter, the result is simply Type . Otherwise, a new function type with no this parameter is created from Type . Generics are erased and only the last overload signature is propagated into the new function type.

This utility does not return a transformed type. Instead, it serves as a marker for a contextual this type. Note that the noImplicitThis flag must be enabled to use this utility.

In the example above, the methods object in the argument to makeObject has a contextual type that includes ThisType and therefore the type of this in methods within the methods object is < x: number, y: number >& < moveBy(dx: number, dy: number): void >. Notice how the type of the methods property simultaneously is an inference target and a source for the this type in methods.

The ThisType marker interface is simply an empty interface declared in lib.d.ts . Beyond being recognized in the contextual type of an object literal, the interface acts like any empty interface.

Intrinsic String Manipulation Types

To help with string manipulation around template string literals, TypeScript includes a set of types which can be used in string manipulation within the type system. You can find those in the Template Literal Types documentation.

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Источник

Искусство типизации: TypeScript Utility Types

Что вы чувствуете от познания нового? За себя скажу, что в такие моменты просветления меня переполняет неподдельная детская радость от свершившегося открытия. Жаль, что этих моментов становится всё меньше. К чему я это? Когда мне в голову мне пришла мысль о написании статьи на эту тему, я сразу вспомнил то ощущение прозрения, которое испытал в момент открытия Utility Types. Всё сразу встало на свои места, и я понял какого кусочка пазла мне всё это время не хватало. Именно о нём я расскажу далее.

TypeScript Utility Types — это набор встроенных типов, которые можно использовать для манипулирования типами данных в коде. Рассмотрим их подробнее.

Awaited

Awaited — это специальный тип, который может быть использован для обозначения типа, который будет возвращен из асинхронной функции.

async function getData(): Promise  < return 'hello'; >let awaitedData: Awaited>; // теперь awaitedData может быть 'hello'

Partial

Partial — делает все свойства объекта типа T необязательными.

interface Person < name: string; age: number; >let partialPerson: Partial; // теперь partialPerson может быть

Required

Required — делает все свойства объекта типа T обязательными.

interface Person < name?: string; age?: number; >let requiredPerson: Required; // теперь requiredPerson может быть

Readonly

Readonly — делает все свойства объекта типа T доступными только для чтения.

interface Point < x: number; y: number; >let readonlyPoint: Readonly; // теперь readonlyPoint может быть

Record

Record — создает тип, который является записью с ключами, определенными в первом параметре, и значениями типа, определенного во втором параметре.

type Keys = 'a' | 'b' | 'c'; type RecordType = Record; let record: RecordType; // теперь record может быть

Pick

Pick — выбирает свойства объекта типа T с ключами, указанными в K.

interface Person < name: string; age: number; >let pickedPerson: Pick; // теперь pickedPerson может быть

Omit

Omit — выбирает свойства объекта типа T, исключая те, которые указаны в K

interface Person < name: string; age: number; >let omittedPerson: Omit; // теперь omittedPerson может быть

Exclude

Exclude — исключает определенные типы из объединенного типа.

type A = 'a' | 'b' | 'c'; type B = Exclude; // теперь B это 'c'

Extract

Extract — извлекает из типа Type только те типы, которые присутствуют в Union.

type A = 'a' | 'b' | 'c'; type B = 'a' | 'b'; type C = Extract; // теперь C это 'a' | 'b'

NonNullable

NonNullable — извлекает тип из Type, исключая null и undefined.

let value: string | null | undefined; let nonNullableValue: NonNullable; // теперь nonNullableValue это string

Parameters

Parameters — извлекает типы аргументов функции Type.

function foo(a: string, b: number) <> type FooParameters = Parameters; // теперь FooParameters это [string, number]

ConstructorParameters

ConstructorParameters — извлекает типы аргументов конструктора Type.

class Foo < constructor(a: string, b: number) <>> type FooConstructorParameters = ConstructorParameters; // теперь FooConstructorParameters это [string, number]

ReturnType

ReturnType — извлекает тип возвращаемого значения функции Type.

function foo(): string < return 'hello'; >type FooReturnType = ReturnType; // теперь FooReturnType это string

InstanceType

InstanceType — извлекает тип экземпляра класса Type.

class Foo < x: number >type FooInstance = InstanceType; // теперь FooInstance это

ThisParameterType

ThisParameterType — извлекает тип this из функции Type.

class Foo < x: number; method(this: this): void < >> type ThisType = ThisParameterType; // теперь ThisType это Foo

OmitThisParameter

OmitThisParameter — определяет функцию без типа this .

class Foo < x: number; method(this: this): void < >> type MethodType = OmitThisParameter; // теперь MethodType это () => void

ThisType

ThisType — добавляет тип this к функции Type.

class Foo < x: number; method(): void < >> type MethodType = ThisType; // теперь MethodType это (this: Foo) => void

Управление регистром

Uppercase , Lowercase , Capitalize , Uncapitalize — это утилитные типы для манипуляции строками, которые изменяют регистр строки в соответствии с их именем.

type Uppercased = Uppercase; // 'HELLO' type Lowercased = Lowercase; // 'hello' type Capitalized = Capitalize; // 'Hello' type Uncapitalized = Uncapitalize; // 'hello'

Заключение

Кто-то скажет: «Большинство из этого не пригодится в реальной работе» — и будет больше прав, чем не прав. Для того чтобы шлёпать формы или писать CRUD’ы не нужно иметь углублённые знания в построении типов, в то время как решение нетривиальной задачи будет найдено быстрее при наличии компетенций в разных направлениях и практиках.

В основе всей моей деятельности лежит именно этот подход. Пришлось спуститься очень глубоко в мир программирования, чтобы найти ответы. Оттуда я и вещаю на своём телеграмм канале.

Источник

Utility Types

TypeScript provides several utility types to facilitate common type transformations. These utilities are available globally.

This type is meant to model operations like await in async functions, or the .then() method on Promise s — specifically, the way that they recursively unwrap Promise s.

Constructs a type with all properties of Type set to optional. This utility will return a type that represents all subsets of a given type.

Constructs a type consisting of all properties of Type set to required. The opposite of Partial .

Constructs a type with all properties of Type set to readonly , meaning the properties of the constructed type cannot be reassigned.

This utility is useful for representing assignment expressions that will fail at runtime (i.e. when attempting to reassign properties of a frozen object).

ts
function freezeType>(obj: Type): ReadonlyType>;

Constructs an object type whose property keys are Keys and whose property values are Type . This utility can be used to map the properties of a type to another type.

Constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type .

Constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals). The opposite of Pick .

Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers .

Constructs a type by extracting from Type all union members that are assignable to Union .

Constructs a type by excluding null and undefined from Type .

Constructs a tuple type from the types used in the parameters of a function type Type .

Constructs a tuple or array type from the types of a constructor function type. It produces a tuple type with all the parameter types (or the type never if Type is not a function).

Constructs a type consisting of the return type of function Type .

Constructs a type consisting of the instance type of a constructor function in Type .

Extracts the type of the this parameter for a function type, or unknown if the function type has no this parameter.

Removes the this parameter from Type . If Type has no explicitly declared this parameter, the result is simply Type . Otherwise, a new function type with no this parameter is created from Type . Generics are erased and only the last overload signature is propagated into the new function type.

This utility does not return a transformed type. Instead, it serves as a marker for a contextual this type. Note that the noImplicitThis flag must be enabled to use this utility.

In the example above, the methods object in the argument to makeObject has a contextual type that includes ThisType and therefore the type of this in methods within the methods object is < x: number, y: number >& < moveBy(dx: number, dy: number): void >. Notice how the type of the methods property simultaneously is an inference target and a source for the this type in methods.

The ThisType marker interface is simply an empty interface declared in lib.d.ts . Beyond being recognized in the contextual type of an object literal, the interface acts like any empty interface.

Intrinsic String Manipulation Types

To help with string manipulation around template string literals, TypeScript includes a set of types which can be used in string manipulation within the type system. You can find those in the Template Literal Types documentation.

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Источник

Читайте также:  Python get today datetime
Оцените статью