Skip to content

Instantly share code, notes, and snippets.

@zyfyy
Last active October 11, 2021 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zyfyy/1fe53e9df20467da6aab25303bc113a2 to your computer and use it in GitHub Desktop.
Save zyfyy/1fe53e9df20467da6aab25303bc113a2 to your computer and use it in GitHub Desktop.
[typescript要点]

extends条件语句汇总

play链接

总结 infer 在被extends判断的条件子语句中定义,返回语句中使用

// 基本extends
/**
 * @example
 * type A1 = 1
 */
type A1 = 'x' extends 'x' ? 1 : 2;

/**
 * @example
 * type A2 = 2
 */
type A2 = 'x' | 'y' extends 'x' ? 1 : 2;

/**
 * @example
 * type A3 = 1 | 2
 */
type P<T> = T extends 'x' ? 1 : 2;
type A3 = P<'x' | 'y'>

type P<T> = [T] extends ['x'] ? 1 : 2;
// type A4 = 2
type A4 = P<'x' | 'y'>






// 常用infer
{
type Unpacked<T> = T extends (infer U)[]
  ? U
  : T extends (...args: any[]) => infer U
  ? U
  : T extends Promise<infer U>
  ? U
  : T;
 
type T0 = Unpacked<string>;
     
type T0 = string
type T1 = Unpacked<string[]>;
     
type T1 = string
type T2 = Unpacked<() => string>;
     
type T2 = string
type T3 = Unpacked<Promise<string>>;
     
type T3 = string
type T4 = Unpacked<Promise<string>[]>;
     
type T4 = Promise<string>
type T5 = Unpacked<Unpacked<Promise<string>[]>>;
     
type T5 = string
}





// infer逆变
{
type Bar<T> = T extends {
  a: (x: infer U) => void;
  b: (x: infer U) => void;
} ? U : never;

// type T1 = string
type T1 = Bar<{ a: (x: string) => void; b: (x: string) => void }>;

// type T2 = never
type T2 = Bar<{ a: (x: string) => void; b: (x: number) => void }>;
}






// infer协变
{
type Foo<T> = T extends {
  a: infer U;
  b: infer U;
} ? U : never;

// type T1 = string
type T1 = Foo<{ a: string; b: string }>;

// type T2 = string | number
type T2 = Foo<{ a: string; b: number }>;
}


/*
作者:愣锤
链接:https://juejin.cn/post/6994102811218673700
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/



import * as React from "react";
declare type Selector<Value> = (value: Value) => any;
declare type SelectorHooks<Selectors> = {
    [K in keyof Selectors]: () => Selectors[K] extends (...args: any) => infer R ? R : never;
};
declare type Hooks<Value, Selectors extends Selector<Value>[]> = Selectors["length"] extends 0 ? [() => Value] : SelectorHooks<Selectors>;
declare type ConstateTuple<Props, Value, Selectors extends Selector<Value>[]> = [
    React.FC<Props>,
    ...Hooks<Value, Selectors>
];
declare function constate<Props, Value, Selectors extends Selector<Value>[]>(useValue: (props: Props) => Value, ...selectors: Selectors): ConstateTuple<Props, Value, Selectors>;
export default constate;
// type PropertyKey = string | number | symbol


type EmptyObject = {
  [K in PropertyKey]: never 
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment