# 再谈泛型-约束关系

453 阅读3分钟

## 约束关系

``````type Func = (p: any) => void

function foo<T extends Func>(p: T) {}

function bar<T>(p: T) {}

foo((p = 1) => {}) // F1
foo((p: number = 1) => {}) // F2

bar((p = 1) => {}) // B1
bar((p: number = 1) => {}) // B2
``````

``````type Func<P = any> = (p: P) => void

function foo<T extends Func>(p: T) {}
``````

``````type Func<P = any> = (p: P) => void

function foo<T>(p: Func<T>) {}

function bar<T>(p: T) {}

foo((p = 1) => {})
``````

``````type Func<P = any> = (p: P) => void

function foo<T = any>(p: Func<T>) {}

function bar<T = any>(p: T = (() => void 0) as any as T) {}

foo((p = 1) => {}) // F1
foo((p: number = 1) => {})

bar() // B1
bar((p: number = 1) => {})
``````

### 无效约束的妙用

``````type Func = <P>(p: P) => void

function foo<T extends Func>(p: T) {}

function bar<T>(p: T) {}

foo((p = 1) => {}) // ts(2322)
foo((p: number = 1) => {}) // ts(2345)
``````

``````type isEqual<A, B> = (<P>() => P extends A ? 1 : 2) extends (<P>() => P extends B ? 1 : 2) ? true : false;
type E1 = isEqual<never, any>;
type E2 = isEqual<any, any>;
``````