Skip to content

Commit

Permalink
ts 오버로딩, 공변성과 반공변성
Browse files Browse the repository at this point in the history
  • Loading branch information
jihunhong committed Oct 5, 2022
1 parent b061136 commit 241b617
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
39 changes: 39 additions & 0 deletions TypeScript/22.10.05 공변성과 반공변성.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
### 공변성과 반공변성

#### 리턴값의 공변성
```ts
function a(x: string): number {
return +x;
}

a('1'); // 1

type B = (x: string) => number | string;
const b: B = a; // (o)
```

type B의 리턴값은 number | string 이지만 ts compile시에는 에러가 발생하지 않는다.

그 이유는 함수의 리턴값은 더 넓은 범위를 따르기 때문에 number | string이 number를 포함하는 관계이므로 대입이 가능해지는 것이다. (반대는 성립하지 않는다.)

> 더 넓은 타입 => 더 좁은 타입 (x)
> 더 좁은 타입 => 더 넓은 타입 (o)

#### 파라미터의 공변성
```ts
function a(x: string | number): number {
return 0;
}

type B = (x: string) => number;
const b: B = a; // (o)
```

파라미터의 타입 범위가 적용되는것은 리턴값과는 반대로 작용한다.

> 더 넓은 타입 => 더 좁은 타입 (o)
> 더 좁은 타입 => 더 넓은 타입 (x)
- 리턴값은 넓은타입으로 향한다.
- 파라미터는 좁은타입으로 향한다.
15 changes: 15 additions & 0 deletions TypeScript/22.10.05 오버로딩.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
### 오버로딩

```ts
declare function add(x: number, y: number): number
declare function add(x: number, y: number, z: number): number

// =>

declare function add(x: number, y: number, z?: number): number

// optional을 이용하는 방법과 두가지 타이핑을 해놓는 방식 모두 가능하다.

add(1, 2);
add(2, 3);
```

0 comments on commit 241b617

Please sign in to comment.