Skip to content

Instantly share code, notes, and snippets.

@TheCubicleBuddha
Last active April 19, 2019 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheCubicleBuddha/c03a1ac37550f8a34df08a3b03915f40 to your computer and use it in GitHub Desktop.
Save TheCubicleBuddha/c03a1ac37550f8a34df08a3b03915f40 to your computer and use it in GitHub Desktop.
This demonstrates how you can use TypeScript to clearly communicate your needs upfront
import { IUserDbInstance, UserDB } from 'UserDatabase';
interface INewUser {
firstName: string,
middleName?: string,
lastName: string
}
function honestDbMethod(newUserToSave: INewUser, dbInstance: IUserDbInstance){
// if(newUserToSave.lastName){ // This if statement is unnecessary because you asked for what you need
// // this will never happen
// }
return dbInstance.save(newUserToSave);
}
honestDbMethod({ firstName: "Madonna" }, UserDB);
// ^ Compliler Error: Property 'lastName' is missing in type '{ firstName: string; }' but required in type 'INewUser'.
@TheCubicleBuddha
Copy link
Author

I left the UserDatabase.ts file for brevity, but here it is:

export interface IUserDbInstance {
    save: (newUser: INewUser)=> INewUser
}

export const UserDB: IUserDbInstance = {
    save: (input)=> {
        console.log(input);
        return input;
    }
}

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