Created
January 19, 2021 14:45
-
-
Save luismisanchez/38878ec01708966175976168cac3306a to your computer and use it in GitHub Desktop.
Typescript Interfaces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Interfaces allow us to create contracts other classes/ objects have to implement | |
// We can use them to define custom types without creating classes | |
// Interfaces ARE NOT compiled to JavaScript! It's just for checking/ validation done by our TypeScript compiler | |
// Example interface | |
interface User { | |
username: string; | |
password: string; | |
confirmPassword?: string; // Optional property => Does not have to be implemented | |
} | |
let user:User; | |
// This value does not satisfy the interface => Compilation error | |
// user = { anything: 'anything', anynumber: 5}; | |
// This value does satisfy the interface | |
user = {username: 'max', password: 'supersecret'}; | |
// Interfaces can also contain functions (without the function body - as it only is a blueprint/ requirement) | |
interface CanDrive { | |
accelerate(speed:number): void; | |
} | |
let car:CanDrive = { | |
accelerate: function (speed:number) { | |
// ... | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment