实现说明
用 satisfies 约束配置对象以函数 resolveTheme为骨架。
使用要点
- 守卫
value === "system"一旦成立就走提前的return,把后续流程挡掉。 - 调用方只需要
config——其余都是内部实现。
常见问题
这段代码会引入外部包吗?
不涉及外部包,每个调用都落在内建 API 上。 文件在加载时定义 resolveTheme。
签名一览:export const config =
核心语句
if (value === "system") return prefersDark ? "dark" : "light";
代码示例
type Theme = "light" | "dark" | "system";
interface AppConfig {
theme: Theme;
locale: string;
features: Record<string, boolean>;
}
export const config = {
theme: "dark",
locale: "en-US",
features: { search: true, beta: false },
} satisfies AppConfig;
// config.theme is inferred as "dark", not widened to Theme:
export type ThemeValue = typeof config.theme;
export function resolveTheme(value: ThemeValue, prefersDark: boolean): "light" | "dark" {
if (value === "system") return prefersDark ? "dark" : "light";
return value;
}