diff --git a/Programming_Languages/TypeScript/Generics.md b/Programming_Languages/TypeScript/Generics.md index 725bc2e..92893df 100644 --- a/Programming_Languages/TypeScript/Generics.md +++ b/Programming_Languages/TypeScript/Generics.md @@ -132,6 +132,56 @@ console.log(allItems); ### GraphQL client for query and mutation requests over `fetch` +```ts +type GraphQlResult = { + data: T; + errors?: Array<{ + message: string; + locations: Array<{ line: number; column: number }>; + path: Array; + }>; +}; + +export class GraphQlClient { + private endpoint: string; + + constructor(endpoint: string) { + this.endpoint = endpoint; + } + async request( + query: string, + variables?: Record + ): Promise { + try { + const response = await fetch(this.endpoint, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ query, variables }), + }); + + if (!response.ok) { + throw new Error( + `Network error: ${response.status} - ${response.statusText}` + ); + } + + const result: GraphQlResult = await response.json(); + + if (result.errors) { + throw new Error(`GraphQL error: ${JSON.stringify(result.errors)}`); + } + + return result.data; + } catch (error) { + console.error(error); + throw error; + } + } +} +``` + ### VSCode extension TreeView generator In VSCode a TreeView is a list of values that may have nested values, like a directory. The following generic is a helper function that generates a TreeView based on a given class that is passed in as an argument, along with the class's constructor values (`args` in the example). It also calls a method `refresh` on each instance of the class. diff --git a/Programming_Languages/TypeScript/Mapped_types.md b/Programming_Languages/TypeScript/Mapped_types.md index 09ded0b..f22a1a3 100644 --- a/Programming_Languages/TypeScript/Mapped_types.md +++ b/Programming_Languages/TypeScript/Mapped_types.md @@ -24,7 +24,9 @@ type Person = { }; ``` -### Read only mapped type +## Main varieties of mapped types + +### Read only Creates a type with all properties of the given type set to `readonly`: @@ -47,7 +49,7 @@ type ReadonlyPerson = { }; ``` -### Partial mapped type +### Partial Creates a type with all properties of the given type set to optional. @@ -70,7 +72,9 @@ type PartialPerson = { }; ``` -### Pick mapped type +### Pick + +This is useful when you want to create a new type based on a subset of properties from an existing type. ```ts type Pick = { @@ -89,31 +93,33 @@ type PersonNameAndAge = { }; ``` -### Record mapped type +### Record -Creates a type with keys of the given type and values of the specified type. +Creates a type with keys of the given type and values of the specified type. It is a way of shoehorning keys from an existing type with new values. -> How does this related to `Record` more generally in TS? - -> How is this different from `Pick` ? +Basic syntax: ```ts -type Record = { - [P in K]: T; -}; - -type PersonRecord = Record<"id", Person>; +Record; ``` -This is equivalent to: +Example: ```ts -type PersonRecord = { - id: Person; +type UserRole = "admin" | "user" | "guest"; + +// Create a Record type to store user role descriptions +type UserRoleDescriptions = Record; + +// Create an object that implements the UserRoleDescriptions type +const roleDescriptions: UserRoleDescriptions = { + admin: "Has full access to the system", + user: "Can access limited resources", + guest: "Can view public resources only", }; ``` -### Exclude mapped type +### Exclude Creates a type by excluding specific properties from the given type. @@ -128,3 +134,47 @@ This is equivalent to: ```ts type KeysWithoutAge = "name" | "city" | "country"; ``` + +### Extract + +Creates a type by extracting specific properties from the given type. Basically the opposite operation to Exclude. + +```ts +type Extract = T extends U ? T : never; + +type NameKey = Extract; +``` + +This is equivalent to: + +```ts +type NameKey = "name"; +``` + +### Non-nullable + +Creates a type by removing null and undefined from the given type. + +```ts +type NonNullable = T extends null | undefined ? never : T; + +type NullablePerson = { + name: string | null; + age: number | null; + city: string | null; + country: string | null; +}; + +type NonNullablePerson = NonNullable; +``` + +Equivalent to: + +```ts +type NonNullablePerson = { + name: string; + age: number; + city: string; + country: string; +}; +```