( << Back) TypeTransformations.ts
1: //https://www.Tscriptlang.org/docs/handbook/utility-Ts.html#recordkeys-type
2: //TypeScript provides several utility types to facilitate common type transformations.
3: // Awaited<T>
4: // Partial<T>
5: // Required<T>
6: // Readonly<T>
7: // Record<Keys, T>
8: // Pick<T, Keys>
9: // Omit<T, Keys>
10: // Exclude<UnionT, ExcludedMembers>
11: // Extract<T, Union>
12: // NonNullable<T>
13: // Parameters<T>
14: // ConstructorParameters<T>
15: // ReturnType<T>
16: // InstanceT<T>
17: // ThisParameterT<T>
18: // OmitThisParameter<T>
19: // ThisType<T>
20: // Intrinsic String Manipulation Ts
21: // Uppercase<StringT>
22: // Lowercase<StringT>
23: // Capitalize<StringT>
24: // Uncapitalize<StringT>
25:
26: console.log(`
27: --- Awaited<Type> --- This type is meant to model operations like await in async functions, or the .then() method on Promise
28: `)
29:
30: type A1 = Awaited<Promise<string>>;
31:
32: type B1 = Awaited<Promise<Promise<number>>>;
33:
34: type C1 = Awaited<boolean | Promise<number>>;
35:
36: console.log(`
37: --- Partial<Type> --- 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.
38: `)
39:
40: interface Todo {
41: title: string;
42: description: string;
43: }
44:
45: function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
46: return { ...todo, ...fieldsToUpdate };
47: }
48:
49: const todo1 = {
50: title: "organize desk",
51: description: "clear clutter",
52: };
53:
54: const todo2 = updateTodo(todo1, {
55: description: "throw out trash",
56: });
57:
58: console.log(`
59: --- Required<Type> --- Constructs a type consisting of all properties of Type set to required.The opposite of Partial.
60: `)
61:
62: interface Props1 {
63: a?: number;
64: b?: string;
65: }
66:
67: const obj1: Props1 = { a: 5 };
68:
69: const obj2: Required<Props1> = { a: 5, b: '' };
70:
71: console.log(`
72: --- Readonly<Type> --- Constructs a type with all properties of Type set to readonly, meaning the properties of the constructed type cannot be reassigned.
73: `)
74:
75: interface Todo1 {
76: title: string;
77: }
78:
79: const todo3: Readonly<Todo1> = {
80: title: "Delete inactive users",
81: };
82:
83: //todo3.title = "Hello"; impossible
84:
85: console.log(`
86: --- Record<Keys, Type> --- Constructs an object type whose property keys are Keys and whose property values are Type.
87: `)
88:
89: interface CatInfo {
90: age: number;
91: breed: string;
92: }
93:
94: type CatName = "miffy" | "boris" | "mordred";
95:
96: const cats: Record<CatName, CatInfo> = {
97: miffy: { age: 10, breed: "Persian" },
98: boris: { age: 5, breed: "Maine Coon" },
99: mordred: { age: 16, breed: "British Shorthair" },
100: };
101:
102: console.log(cats.boris);
103:
104: console.log(`
105: --- Pick<Type, Keys> --- Constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type
106: `)
107:
108: interface Todo2 {
109: title: string;
110: description: string;
111: completed: boolean;
112: }
113:
114: type TodoPreview = Pick<Todo2, "title" | "completed">;
115:
116: const todo4: TodoPreview = {
117: title: "Clean room",
118: completed: false,
119: };
120:
121: console.log(todo4);
122:
123: console.log(`
124: --- Omit<Type, Keys> --- Constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals). The opposite of Pick.
125: `)
126:
127: interface Todo5 {
128: title: string;
129: description: string;
130: completed: boolean;
131: createdAt: number;
132: }
133:
134: type TodoPreview5 = Omit<Todo5, "description">;
135:
136: const todo5: TodoPreview5 = {
137: title: "Clean room",
138: completed: false,
139: createdAt: 1615544252770,
140: };
141:
142: console.log(todo5);
143:
144: type TodoInfo5 = Omit<Todo5, "completed" | "createdAt">;
145:
146: const todoInfo5: TodoInfo5 = {
147: title: "Pick up kids",
148: description: "Kindergarten closes at 5pm",
149: };
150:
151: console.log(todoInfo5);
152:
153: console.log(`
154: --- Exclude<UnionType, ExcludedMembers> --- Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers.
155: `)
156:
157: type T0 = Exclude<"a" | "b" | "c", "a">;
158:
159: type T6 = Exclude<"a" | "b" | "c", "a" | "b">;
160:
161: type T7 = Exclude<string | number | (() => void), Function>;
162:
163: type Shape =
164: | { kind: "circle"; radius: number }
165: | { kind: "square"; x: number }
166: | { kind: "triangle"; x: number; y: number };
167:
168: type T8 = Exclude<Shape, { kind: "circle" }>
169:
170: console.log(`
171: --- Extract<Type, Union> --- Constructs a type by extracting from Type all union members that are assignable to Union
172: `)
173:
174: type T10 = Extract<"a" | "b" | "c", "a" | "f">;
175:
176: type T11 = Extract<string | number | (() => void), Function>;
177:
178: type Shape1 =
179: | { kind: "circle"; radius: number }
180: | { kind: "square"; x: number }
181: | { kind: "triangle"; x: number; y: number };
182:
183: type T12 = Extract<Shape, { kind: "circle" }>
184:
185: console.log(`
186: --- NonNullable<Type> --- Constructs a type by excluding null and undefined from Type.
187: `)
188:
189: type T13 = NonNullable<string | number | undefined>;
190:
191: type T14 = NonNullable<string[] | null | undefined>;
192:
193: console.log(`
194: --- Parameters<Type> --- Constructs a tuple type from the types used in the parameters of a function type Type.
195: `)
196:
197: declare function f1(arg: { a: number; b: string }): void;
198:
199: type T15 = Parameters<() => string>;
200:
201: type T16 = Parameters<(s: string) => void>;
202:
203: type T17 = Parameters<<T>(arg: T) => T>;
204:
205: type T18 = Parameters<typeof f1>;
206:
207: type T19= Parameters<any>;
208:
209: type T20 = Parameters<never>;
210:
211: console.log(`
212: --- ConstructorParameters<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).
213: `)
214:
215: type T21 = ConstructorParameters<ErrorConstructor>;
216:
217: type T22 = ConstructorParameters<FunctionConstructor>;
218:
219: type T23 = ConstructorParameters<RegExpConstructor>;
220:
221: class C2 {
222: constructor(a: number, b: string) {}
223: }
224: type T24 = ConstructorParameters<typeof C2>;
225:
226: type T25 = ConstructorParameters<any>;
227:
228: console.log(`
229: --- ReturnType<Type> --- Constructs a type consisting of the return type of function Type.
230: `)
231:
232: declare function f2(): { a: number; b: string };
233:
234: type T26 = ReturnType<() => string>;
235:
236: type T27 = ReturnType<(s: string) => void>;
237:
238: type T28 = ReturnType<<T>() => T>;
239:
240: type T29 = ReturnType<<T extends U, U extends number[]>() => T>;
241:
242: type T30 = ReturnType<typeof f2>;
243:
244: type T31 = ReturnType<any>;
245:
246: type T32 = ReturnType<never>;
247:
248: console.log(`
249: --- InstanceType<Type> --- Constructs a type consisting of the instance type of a constructor function in Type.
250: `)
251:
252: class C3 {
253: x = 0;
254: y = 0;
255: }
256:
257: type T33 = InstanceType<typeof C3>;
258:
259: type T34 = InstanceType<any>;
260:
261: type T35 = InstanceType<never>;
262:
263: console.log(`
264: --- ThisParameterType<Type> --- Extracts the type of the this parameter for a function type, or unknown if the function type has no this parameter.
265: `)
266:
267: function toHex(this: Number) {
268: return this.toString(16);
269: }
270:
271: function numberToString(n: ThisParameterType<typeof toHex>) {
272: return toHex.apply(n);
273: }
274:
275: console.log(`
276: --- OmitThisParameter<Type> --- Removes the this parameter from Type
277: `)
278:
279: const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);
280:
281: console.log(fiveToHex());
282:
283: console.log(`
284: --- ThisType<Type> --- This utility does not return a transformed type. Instead, it serves as a marker for a contextual this type. noImplicitThis flag must be enabled to use this utility.
285: `)
286:
287: type ObjectDescriptor<D, M> = {
288: data?: D;
289: methods?: M & ThisType<D & M>; // Type of 'this' in methods is D & M
290: };
291:
292: function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M {
293: let data: object = desc.data || {};
294: let methods: object = desc.methods || {};
295: return { ...data, ...methods } as D & M;
296: }
297:
298: let obj3 = makeObject({
299: data: { x: 0, y: 0 },
300: methods: {
301: moveBy(dx: number, dy: number) {
302: this.x += dx; // Strongly typed this
303: this.y += dy; // Strongly typed this
304: },
305: },
306: });
307:
308: obj3.x = 10;
309: obj3.y = 20;
310: obj3.moveBy(5, 5);
311:
312: // Intrinsic String Manipulation Types
313: // Uppercase<StringType>
314: // Lowercase<StringType>
315: // Capitalize<StringType>
316: // Uncapitalize<StringType>
Front context:
Comments (
)
Link to this page:
http://www.vb-net.com/TypescriptLearningStartPoint/TypeTransformations.htm
|