Loading...
Loading...
Compare original and translation side by side
type PhoneNumber = string & { __brand: "PhoneNumber" };
function parsePhone(input: string): PhoneNumber {
if (!/^\+?\d{10,15}$/.test(input)) throw new Error(`Invalid: ${input}`);
return input as PhoneNumber;
}
function sendSMS(to: PhoneNumber, body: string) {
/* input is trusted */
}type PhoneNumber = string & { __brand: "PhoneNumber" };
function parsePhone(input: string): PhoneNumber {
if (!/^\+?\d{10,15}$/.test(input)) throw new Error(`Invalid: ${input}`);
return input as PhoneNumber;
}
function sendSMS(to: PhoneNumber, body: string) {
/* input is trusted */
}// Don't — invalid combos representable
type State = { loading: boolean; user?: User; error?: string };
// Do — only valid states exist
type State =
| { status: "loading" }
| { status: "success"; user: User }
| { status: "error"; error: string };// 不推荐——可表示无效组合
type State = { loading: boolean; user?: User; error?: string };
// 推荐——仅存在有效状态
type State =
| { status: "loading" }
| { status: "success"; user: User }
| { status: "error"; error: string };users.emailEmailPickOmitParametersReturnTypeAwaitedtypeof// Don't — duplicate shape, drifts when the row changes
type UserSummary = { id: string; email: Email };
function renderUser(u: UserSummary) {
/* ... */
}
// Do — derive from the source of truth
type User = Awaited<ReturnType<typeof db.query.users.findFirst>>;
function renderUser(u: Pick<User, "id" | "email">) {
/* ... */
}Emailusers.emailPickOmitParametersReturnTypeAwaitedtypeof// 不推荐——重复结构,当数据行变化时会不一致
type UserSummary = { id: string; email: Email };
function renderUser(u: UserSummary) {
/* ... */
}
// 推荐——从可信数据源推导
type User = Awaited<ReturnType<typeof db.query.users.findFirst>>;
function renderUser(u: Pick<User, "id" | "email">) {
/* ... */
}// Don't — swap two args, still compiles
sendEmail("Welcome!", "Hi there");
// Do — order-independent, self-documenting
sendEmail({ to: "alice@x.com", body: "Hi there" });// 不推荐——交换两个参数仍能编译通过
sendEmail("Welcome!", "Hi there");
// 推荐——与顺序无关,自文档化
sendEmail({ to: "alice@x.com", body: "Hi there" });StandardSchemaV1<unknown, T>StandardSchemaV1<unknown, T>bun:sqlitebun:sqlite