[TypeScript] 04 Decoding Perplexing

BASIC string, number, boolean, union
TYPE MANIPULATION generics, conditionals, keys, infer, mapped types + modifiers, index access
UTILITY TYPES exclude, extractpick, omit
OBJECT TYPES optional properties

Use generics, unions, conditionals

type IsTruthy<T> = T extends null | undefined | false | 0 | "" ? false : true;

// equals

type IsTruthy<Y> =
if: T extends null | undefined | false | 0 | ""
then: false
else: true;

Use utility types

utility types 是一类TS提供的MappedTypes,常用如下:
  • Exclude, Returns the provided union, minus any union items to exclude.
  • Pick, Return a new type from the provided type with the keys.
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

type ValidDoubleObject<T> = T extends { a: infer U; b: infer U } ? U : never;

// IDE Loose Autocomplete,加上 (string & {}); 只加 string,ModelNames就是string,Autocomplete会失败;
type ModelNames = "gpt-4o" | "o3-mini" | "claude-sonnet-latest" | (string & {});
const model: ModelNames = "others"; // 此处可以显示正确的 Autocomplete

Use mapped types

// -? means remove optional modifier(去掉 Optional 标识).
type MappedValidType<T> = {[K in keyof T]-?: true};
type ValidKeyUnion<T> = {[K in keyof T]-?: true}[keyof T];

type ValidKeys<T> = {
[K in keyof T]-?: (Exclude<T[K], null>) extends { a: infer U; b: infer U }
? IsTruthy<U> extends true ? K : never
: never
}[keyof T]

// 对于 Complex Type,运用该 util 可使得 type 一目了然
type Prettify<T> = { [K in keyof T]: T[K]} & {};

Date:
Words:
320
Time to read:
1 min