Last active
August 29, 2015 14:17
-
-
Save laser/033b1e489139ac889782 to your computer and use it in GitHub Desktop.
Type Aliases for Object Types as Interfaces
This file contains hidden or 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
/* @flow */ | |
/////////////////////////////////////////////////////////// | |
// Types and Classes | |
// | |
class User { | |
n: number; | |
constructor(n) { | |
this.n = n; | |
} | |
} | |
class CustomError { | |
message: string; | |
constructor(m) { | |
this.message = m; | |
} | |
} | |
type NodeCallback<E, V> = (err: ?E, value: ?V) => void; | |
type UserDAOIFace = { | |
getUserById: (x: number, callback: NodeCallback<CustomError, User>) => void; | |
} | |
var userDAOImpl: UserDAOIFace = { | |
getUserById(id, callback) { | |
/* pretend that we delegate to a MongoDB client or something */ | |
if (id === 555) { | |
callback(new CustomError("User not found!"), undefined); | |
} | |
else { | |
callback(null, new User(id)); | |
} | |
} | |
} | |
var fakeUserDAOImpl: UserDAOIFace = { | |
getUserById(id, callback) { | |
callback(null, new User(555)); | |
} | |
} | |
class UserService { | |
dao: UserDAOIFace; | |
constructor(dao) { | |
this.dao = dao; | |
} | |
getUserById(userId: number, callback: NodeCallback): void { | |
this.dao.getUserById(userId, callback); | |
} | |
} | |
/////////////////////////////////////////////////////////// | |
// Usage | |
// | |
var u = new UserService(userDAOImpl); | |
u.getUserById(444, function(err, user) { | |
console.log(JSON.stringify(user)); | |
}); | |
u.getUserById(555, function(err, user) { | |
if (err) { | |
console.log(JSON.stringify(err.message)); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment