-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
- 리턴값은 넓은타입으로 향한다. | ||
- 파라미터는 좁은타입으로 향한다. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
``` |