방명록
- 2. Readonly2023년 08월 02일 02시 09분 40초에 업로드 된 글입니다.작성자: sooooong_minseok
type MyReadonly<T> = any /* _____________ 테스트 케이스 _____________ */ import type { Equal, Expect } from '@type-challenges/utils' type cases = [ Expect<Equal<MyReadonly<Todo1>, Readonly<Todo1>>>, ] interface Todo1 { title: string description: string completed: boolean meta: { author: string } }
키워드1. Readonly 읽기전용
Readonly타입 매핑을 이용하여 T 타입을 받고 그 타입의 모든 속성을 readonly로 지정하는 Readonly라는 타입이 있습니다. 여기에 실제로 이걸 사용하는 데모가 나와 있습니다:따라서,
any는 모든 속성을 readonly로 지정하여, Readonly라는 작업이 필요함. 비용증가.
https://radlohead.gitbook.io/typescript-deep-dive/type-system/readonly
다양한 사용 사례
1. ReactJS ->
하지만 React의 타입 정의가 이들을 이미 readonly로 표기하고 있기 때문에 직접 이렇게 할 필요는 없습니다 (내부적으로 인자로 전달된 제네릭 타입을 앞서 설명한 Readonly 타입으로 감쌈).
interface Props { readonly foo: number; } interface State { readonly bar: number; } export class Something extends React.Component<Props,State> { someMethod() { // 아래와 같은 일이 발생할 수 없음을 확신할 수 있음 this.props.foo = 123; // 오류: (props는 불변임) this.state.baz = 456; // 오류: (this.setState를 사용해야 함) } }
2. 편리한 불변성 지원
/** * 선언 */ interface Foo { readonly[x: number]: number; } /** * 사용 */ let foo: Foo = { 0: 123, 2: 345 }; console.log(foo[0]); // 오케이 (읽기) foo[0] = 456; // 오류 (변경하기): readonly 임
let foo: ReadonlyArray<number> = [1, 2, 3]; console.log(foo[0]); // 오케이 foo.push(4); // 오류: `push`는 배열을 상태를 바꾸므로 ReadonlyArray에 존재하지 않음 foo = foo.concat([4]); // 오케이: 복사본 생성
3. 자동 추론경우에 따라 컴파일러가 자동으로 특정 항목이 읽기 전용임을 추론해낼 수 있습니다. 즉, 클래스에 속성이 있지만 게터(getter)만 있고 세터(setter)가 없다면 컴파일러는 그 속성을 readonly인 것으로 간주합니다. 예를 들면:class Person { firstName: string = "John"; lastName: string = "Doe"; get fullName() { return this.firstName + this.lastName; } } const person = new Person(); console.log(person.fullName); // John Doe person.fullName = "Dear Reader"; // 오류! fullName은 readonly
키워드2. Readonly vs const
const
1. 변수 참조를 위한 것2. 변수에 다른 값을 할당/대입할 수 없음1. const foo = 123; // 변수 참조
readonly
1. 속성을 위한 것
2. 속성을 앨리어싱을 통해 변경될 수 있음1. var bar: { readonly bar: number; // 속성의 경우 } 2. let foo: { readonly bar: number; } = { bar: 123 }; function iMutateFoo(foo: { bar: number }) { foo.bar = 456; } iMutateFoo(foo); // foo 인자가 foo 파라미터에 의해 앨리어싱됨 console.log(foo.bar); // 456!
'프로그래밍언어 > typescript' 카테고리의 다른 글
4. First of Array (0) 2023.08.09 3. Tuple of Object (0) 2023.08.09 1. Pick (0) 2023.07.22 다음글이 없습니다.이전글이 없습니다.댓글