基本类型推断 Basic Type Inference

  1. // example1:推断函数返回值类型
  2. function inferred() {
  3. const a = 'hi'
  4. return a
  5. }
  6. // example2:从接口定义推断类型
  7. interface DefinesTypes {
  8. inferred: (first: number, second: string) => number
  9. }
  10. const f: DefinesTypes = {
  11. inferred(first, second) {
  12. return first + second.length
  13. }
  14. }

泛型推断 Inference With Generics

// the example from typescript's docs
// 类型T没明确制定,但是可以支持keyof的任何类型
function getProperty<T, K extends keyof T>(obj: T, key: K) {
    return obj[key];
}

let x = { a: 1, b: 2, c: 3, d: 4 };

getProperty(x, "a"); // okay
getProperty(x, "m"); // error: Argument of type 'm' isn't assignable to 'a' | 'b' | 'c' | 'd'.

// new example not in the typescript docs:
const y = { totally: 'different' }

getProperty(y, "a"); // error: Argument of type 'a' isn't assignable to 'totally'.
getProperty(y, "totally"); // okay

A Real-World Example

interface Action<T = any> { type: T }
interface AnyAction extends Action { [extraProps: string]: any }

type Reducer<S = any, A extends Action = AnyAction> = (
  state: S | undefined,
  action: A
) => S

interface Store<S = any, A extends Action = AnyAction> {
  getState(): S
  dispatch(action: A): A
  replaceReducer<NewState = S, NewActions extends A = A>(
    nextReducer: Reducer<NewState, NewActions>
  ): Store<NewState, NewActions>
}

export type StoreEnhancer<StoreExt = {}, StateExt = {}> = (
  next: StoreEnhancerStoreCreator
) => StoreEnhancerStoreCreator<StoreExt, StateExt>

export type StoreEnhancerStoreCreator<StoreExt = {}, StateExt = {}> = <
  S = any,
  A extends Action = AnyAction
>(
  reducer: Reducer<S, A>,
  preloadedState?: S
) => Store<S & StateExt, A> & StoreExt

参考: