add typestate typescript example
This commit is contained in:
1 parent
e42d897d41
commit
1d9a7fa4fe
4 files changed
+33
-2
No files matched your search
@@ -0,0 +1,30 @@
|
||||
type State = "locked" | "unlocked";
|
||||
|
||||
class CredentialManager<S extends State> {
|
||||
private readonly state?: S;
|
||||
|
||||
unlock(this: CredentialManager<"locked">, master_key: string) {
|
||||
return this as unknown as CredentialManager<"unlocked">;
|
||||
}
|
||||
|
||||
set(this: CredentialManager<"unlocked">, key: string, value: any) {
|
||||
// ...
|
||||
}
|
||||
|
||||
get(this: CredentialManager<"unlocked">, key: string): string | undefined {
|
||||
// ...
|
||||
return undefined;
|
||||
}
|
||||
|
||||
lock(this: CredentialManager<"unlocked">): CredentialManager<"locked"> {
|
||||
return this as unknown as CredentialManager<"locked">;
|
||||
}
|
||||
}
|
||||
|
||||
function main2() {
|
||||
let pw_locked = new CredentialManager<"locked">();
|
||||
let pw_unlocked = pw_locked.unlock("psst");
|
||||
pw_unlocked.set("foo", "bar");
|
||||
let val = pw_unlocked.get("foo");
|
||||
pw_locked = pw_unlocked.lock();
|
||||
}
|
||||
Reference in new issue
Block a user