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();
|
||||
}
|
||||
@@ -30,7 +30,7 @@ class WebSocketClient {
|
||||
}
|
||||
}
|
||||
|
||||
function main_ws() {
|
||||
function main1() {
|
||||
const client = new WebSocketClient();
|
||||
client.send(OpCode.PING, {});
|
||||
}
|
||||
@@ -23,7 +23,7 @@ function navigate<P extends string>(path: P, params: ParseUrlParams<P>) {
|
||||
// ...
|
||||
}
|
||||
|
||||
function main() {
|
||||
function main3() {
|
||||
navigate("/hello", {});
|
||||
navigate("/hello/{name}", { name: "foo" });
|
||||
navigate("/book/{author}/{id}", { author: "foo", id: "bar" });
|
||||
@@ -1,2 +1,3 @@
|
||||
[workspace]
|
||||
members = ["01-problem", "02-runtime-check", "03-builder-pattern", "04-typestate"]
|
||||
resolver = "3"
|
||||
Reference in new issue
Block a user