Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

typescript in out keyword #61

Open
youngkyo0504 opened this issue Aug 3, 2024 · 0 comments
Open

typescript in out keyword #61

youngkyo0504 opened this issue Aug 3, 2024 · 0 comments

Comments

@youngkyo0504
Copy link
Owner

youngkyo0504 commented Aug 3, 2024

템플릿 예시입니다.

title:
full_path: src/pages/.md

TypeScript: Documentation - TypeScript 4.7

기존 Typescript는 공변과 반공변을 명시적으로 적을 수 있는 키워드가 없었다.

T에 대해 공변일때는 다음과 같이 쓰면된다.

type Getter<out T> = () => T

반공변일때는 in을 쓰자

type Setter<in T> = (value : T ) => void

in , out 그저 input과 output으로 생각해보자
만약 다음과 같이 T에 대해서 input, output에 둘다 쓰이는 타입이라면 in out을 둘다 쓴다.
이런 것은 inVariant라고 부른다.

interface State<in out T> {
    get: () => T;
    set: (value: T) => void;
}

State and State aren’t substitutable for the other.

in out이 없어도 아래는 false다
type B = State extends State ? true : false
type B = State extends State ? true : false

구조적 타이핑에서는 invariant, variant, coVariant를 명시하지 않아도 알아서 추론된다.
이 키워드를 사용하는 이유는 뭔가?

  1. 코드를 보는 사람에게 명시적으로 알려주기 위함이다.
  2. 속도와 정확성을 위해서다. 기존에는 공변, 반공변을 추론하지만 명시적으로 적으면 추론하는 비용을 아낄 수 있다.

그리고 공변과 반공변을 정확히 계산할 수 없는 경우도 있다고 한다.(? 명확하지않음) 타입스크립트 공식문서에는 다음과 같은 예시가 있다.

계산에서 정확하게 해결할 수 없는 순환을 발견하여 유형의 분산에 대한 명확한 답이 없는 경우가 종종 있습니다.

type Foo<T> = {
    x: T;
    f: Bar<T>;
}
type Bar<U> = (x: Baz<U[]>) => void;
type Baz<V> = {
    value: Foo<V[]>;
}
declare let foo1: Foo<unknown>;
declare let foo2: Foo<string>;
foo1 = foo2;  // Should be an error but isn't ❌
foo2 = foo1;  // Error - correct ✅
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant