Skip to content

Instantly share code, notes, and snippets.

@smolijar
Last active November 28, 2018 09:20
Show Gist options
  • Save smolijar/4d329c40f7996e297f65bf2c44d6af20 to your computer and use it in GitHub Desktop.
Save smolijar/4d329c40f7996e297f65bf2c44d6af20 to your computer and use it in GitHub Desktop.
omit_type
author tags
Jaroslav Šmolík
typescript
omit
meta type
generic type

Omit type and meta programming

Post entity

interface PostAttributes {
    id: number;
    text: string;
    userId: number;
    title: string; // required attribute you forget about
}

Post template for new post

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 '...'

Force cast it (no need for any! ✨)

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!

Using Omit type

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

Omitting more attributes

// omit more attributes!
Omit<MyType, 'a'|'b'|'c'>

Support

Omit is not native, however is in lodash, ramda

Generic native meta types

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>;

Summary

🎓 Slight type changes are very common, use meta-types and dont rape TS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment