Merging Objects together
- function merge<O, T>(data1: O, data2: T): O | T {
+ function merge<O, T>(master: O, myFeatureBranchFrom3MonthsAgo: T): O | T {
return {
- ...data1,
- ...data2,
+ ...master,
+ ...myFeatureBranchFrom3MonthsAgo,
};
}
type Merge<O, T> = Omit<O, keyof T> & T;
- function merge<O, T>(data1: O, data2: T): Merge<O, T> {
+ function merge<O, T>(master: O, myFeatureBranchFrom3MonthsAgo: T): Merge<O, T> {
return {
- ...data1,
- ...data2,
+ ...master,
+ ...myFeatureBranchFrom3MonthsAgo,
};
}
@@ -598,25 +598,30 @@
Distinguish union types
- interface TypeA {
- type: 'A';
+ enum Type {
+ A = 'A',
+ B = 'B',
+ }
+
+ interface ImagineCoolExampleName {
+ type: Type.A;
foo: string;
bar: string;
}
- interface TypeB {
- type: 'B';
+ interface ImTooLazyToThinkOfRealWorldExamples {
+ type: Type.B;
foo: number;
blubb: string;
}
- function distinguishType(type: TypeA | TypeB) {
- if (type.type === 'A') {
- type.foo.includes('whatever');
- type.bar;
+ function distinguishType(obj: ImagineCoolExampleName | ImTooLazyToThinkOfRealWorldExamples) {
+ if (obj.type === Type.A) {
+ obj.foo.includes('whatever');
+ obj.bar;
} else {
- type.blubb.includes('something');
- type.foo.toFixed(2);
+ obj.blubb.includes('something');
+ obj.foo.toFixed(2);
}
}
@@ -632,8 +637,8 @@
2: 'c',
};
- function filterByKeys(keys: (keyof typeof someObj)[]) {
- keys.map(key => someObj[key]);
+ function filterByKeys(keys: (keyof typeof someObj)[]): ((typeof someObj)[keyof typeof someObj])[] {
+ return keys.map(key => someObj[key]);
}
filterByKeys(Object.keys(someObj)); // error
@@ -684,8 +689,8 @@
2: 'c',
};
- function filterByKeys(keys: (keyof typeof someObj)[]) {
- keys.map(key => someObj[key]);
+ function filterByKeys(keys: (keyof typeof someObj)[]): ((typeof someObj)[keyof typeof someObj])[] {
+ return keys.map(key => someObj[key]);
}
function getKeysFromObject<
@@ -801,4 +806,4 @@