本日の学習 - frontend(8/20)

2025-08-20
  • 本日の学習 - frontend
    • CVA(Class Variance Authority)
  • Tailwind などのユーティリティクラスを**「バリアント(状態・バリエーション)」で切り替えるための関数群**
  • variant: 種類・バリエーション、intent: その中でもデザイン上の意図を表すもの
    • as consts
const b = 'text' as const;
//値はtextで、型は `text` だけという型になる

const SIZES = ['sm', 'md', 'lg'] as const;
type Size = typeof SIZES[number];
// 'sm' | 'md' | 'lg' というユニオン型になる
- typeof演算子
  • TSのtypeofはJSとは全く異なる
  • 変数やオブジェクトから型定義を取り出す
const obj = { "a": "100", "b": "200" };
type T = typeof obj;

type T = {
  a: string;
  b: string;
}
// keyはそのまま、値が型となる
  • 関数に指定することもできる、関数に指定すると、その関数の引数・戻り値の型を作る
function add(x: number, y: number): number {
  return x + y;
}
type AddType = typeof add;

// type AddType = (x: number, y: number) => number;

Parameter, ReturnTypeなどを使うことでパラメータや返り値だけを返すことができる
function greet(name: string, age: number): string {
  return `Hello ${name} (${age})`;
}

type GreetParams = Parameters<typeof greet>; 
// [string, number]

type GreetReturn = ReturnType<typeof greet>; 
// string
- keyof演算子
  • 与えられたオブジェクトからUnion型を作成する
const obj = { a: 1, b: 2, c: 3 };
type Keys = keyof typeof obj;
// type Keys = "a" | "b" | "c";
- ジェネリック型
// VariantProps という型(ジェネリク)を用意しているライブラリがある
type VariantProps<T> = ... // T から props 型を抽出する仕組み
                                                      
// inputVariants は cva() の戻り値
const inputVariants = cva(...);

// ここで typeof で inputVariants の型を取り出し
export type InputVariantProps = VariantProps<typeof inputVariants>;
- 型と型エイリアス
  • 型は値の型を表す、型エイリアスは名前をつける。 export type UserId = string はUserId という名前をつけただけなので、型エイリアス
    • Omit
  • TypeScriptの標準のユーティリティ型
  • TypeScriptに最初から用意されている型を変換するための汎用ツール
  • イメージとしては型のための変換・生成関数
  • Omit<T, K> = T型からKに指定したキーを取り除いた型を作る
    • Interface
  • 型を定義する手段なので、これも型、オブジェクトの形を定義する専用の構文
  • extendsで感まで区切ることで複数のInterface、あるいは型を合体させた型(Interface)を定義できる
  • 型エイリアスはユニオン、条件型などがかける
    • 条件型・ジェネリックな変換
  • inferを使うと、string[] -> stringにしたりできる
    • never 絶対に値が存在しない型
type NonNullable<T> = T extends null | undefined ? never : T;
type T1 = NonNullable<string | null>;      // string
  • まだ理解が浅い