author | tags | ||||
---|---|---|---|---|---|
Jaroslav Šmolík |
|
interface PostAttributes {
id: number;
text: string;
userId: number;
title: string; // required attribute you forget about
}
Creating Post entity template to use in tests
let postToCreate: PostAttributes;
// ...
postToCreate = {
text: 'How much wood would a woodchuck chuck, if woodchuck could chuck wood',
userId: ranSeeds.users.find(/*...*/).id
};
❌ TS unhappy
Property 'id' is missing in type '...'
postToCreate = {
text: 'How much wood would a woodchuck chuck, if woodchuck could chuck wood',
userId: ranSeeds.users.find(/*...*/).id
} as PostAttributes;
✔️ Works like a charm
But forgot about title!
let postToCreate: Omit<PostAttributes, 'id'>;
postToCreate = {
text: 'How much wood would a woodchuck chuck, if woodchuck could chuck wood',
};
❌ TS rightfully unhappy!
Property 'title' is missing in type '...'
let postToCreate: Omit<PostAttributes, 'id'>;
postToCreate = {
text: 'How much wood would a woodchuck chuck, if woodchuck could chuck wood',
title: 'Woodchuck'
};
✔️ Works like a charm
// omit more attributes!
Omit<MyType, 'a'|'b'|'c'>
Omit
is not native, however is in lodash
, ramda
From lib.es5.d.ts
(see compilerOptions.target
in tsconfig
)
// Make all properties in T optional
type Partial<T>;
// Make all properties in T required
type Required<T>;
// Make all properties in T readonly
type Readonly<T>;
// From T pick a set of properties K
type Pick<T, K extends keyof T>;
// Construct a type with a set of properties K of type T
type Record<K extends keyof any, T>;
// Exclude from T those types that are assignable to U
type Exclude<T, U>;
// Extract from T those types that are assignable to U
type Extract<T, U>;
// Exclude null and undefined from T
type NonNullable<T>;
// Obtain the parameters of a function type in a tuple
type Parameters<T extends (...args: any[]) => any>;
// Obtain the parameters of a constructor function type in a tuple
type ConstructorParameters<T extends new (...args: any[]) => any>;
// Obtain the return type of a function type
type ReturnType<T extends (...args: any[]) => any>;
// Obtain the return type of a constructor function type
type InstanceType<T extends new (...args: any[]) => any>;
🎓 Slight type changes are very common, use meta-types and dont rape TS.