メインコンテンツにスキップ

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 はオプションの 2 番目の型型引数も受け付けます。

高度なユースケース: `VarGroup` の一意な型 ID

TypeScript (および Flow) は構造的型付けを使用します。つまり、形状が同じ 2 つのオブジェクトは同じ型とみなされます。ただし、stylex.defineVars を使用するたびに、新しい変数のセットが作成されます。

作成された各 VarGroup に一意の型 ID があると便利で、それらを区別して特定の VarGroup のテーマのみを受け付けることができます。これは「名目型付け」としても知られており、VarGroup の 2 番目の型引数に一意のシンボルを使用することで実現できます。

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 は形状は同じですが、2 つの異なる型 ID を持つ VarGroup オブジェクトです。これにより、一方の Theme がもう一方で使用できないようにします。

形状が同じ 2 つの異なる VarGroup オブジェクトが定義されることはまれなため、ほとんどの場合この機能は必要ありません。どうしても必要な稀なケースで使用できます。