基本类型推断 Basic Type Inference
// example1:推断函数返回值类型
function inferred() {
const a = 'hi'
return a
}
// example2:从接口定义推断类型
interface DefinesTypes {
inferred: (first: number, second: string) => number
}
const f: DefinesTypes = {
inferred(first, second) {
return first + second.length
}
}
泛型推断 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
参考: