跳至主要内容

VarGroup<>

type VarGroup<Tokens extends {}>

一个 VarGroup 是调用 stylex.defineVars 后生成的对象的类型。它将键映射到 CSS 自定义属性的引用。

VarGroup 也是 stylex.createTheme 的第一个参数的必需类型。

通常,不需要显式使用 VarGroup,因为它可以从 stylex.defineVars 的参数中推断出来。

import * as stylex from '@stylexjs/stylex';

export const vars = stylex.defineVars({
color: 'red',
backgroundColor: 'blue',
});

export type Vars = typeof vars;
/*
Vars = VarGroup<{
color: string,
backgroundColor: string,
}>
*/

但是,在某些情况下,可能需要显式使用 VarGroup,以约束主题内变量的值。

import * as stylex from '@stylexjs/stylex';
import type {VarGroup} from '@stylexjs/stylex';

const vars: VarGroup<{
color: 'red' | 'blue' | 'green' | 'yellow',
backgroundColor: 'red' | 'blue' | 'green' | 'yellow',
}> = stylex.defineVars({
color: 'red',
backgroundColor: 'blue',
});

现在,当为 vars 创建主题时,colorbackgroundColor 的值只能是指定值之一。

import * as stylex from '@stylexjs/stylex';
import {vars} from './vars.stylex';

export const theme1 = stylex.createTheme(vars, {
color: 'red', // OK
backgroundColor: 'blue', // OK
});

export const theme2 = stylex.createTheme(vars, {
// Error: 'orange' is not assignable to 'red' | 'blue' | 'green' | 'yellow'
color: 'orange',
});

虽然在大多数情况下不需要,但 VarGroup 也接受一个可选的第二个类型参数。

高级用例:`VarGroup` 的唯一类型标识

TypeScript(和 Flow)使用结构化类型,这意味着两个具有相同形状的对象被认为是相同的类型。但是,每次使用 stylex.defineVars 都会产生一组新的变量。

为每个创建的 VarGroup 提供一个唯一的类型标识可能很有用,以便能够区分它们并仅为特定 VarGroup 接受主题。这也被称为“名义类型”,可以通过使用唯一的符号作为 VarGroup 的第二个类型参数来实现。

VarGroup 的完整类型签名为

type VarGroup<Tokens extends {}, ID extends symbol = symbol>

它可以这样使用

import * as stylex from '@stylexjs/stylex';
import type {VarGroup} from '@stylexjs/stylex';

type Shape = {
color: string,
backgroundColor: string,
};

declare const BaseColors: unique symbol;
export const baseColors: VarGroup<Shape, typeof BaseColors> =
stylex.defineVars({
color: 'red',
backgroundColor: 'blue',
});

declare const CardColors: unique symbol;
export const cardColors: VarGroup<Shape, typeof CardColors> =
stylex.defineVars({
color: 'red',
backgroundColor: 'blue',
});

这里 baseColorscardColors 是具有相同形状但具有两个不同类型标识的 VarGroup 对象。这确保了一个对象的 Theme 不能用于另一个对象。

定义两个具有相同形状的不同 VarGroup 对象的情况应该很少见,因此在大多数情况下不需要此功能。在少数需要的情况下,它可用。