Recent Posts
Recent Comments
Link
Today
Total
05-09 00:27
관리 메뉴

채린씨의 티스토리

[TypeChallenges] 7. Readonly (easy) 본문

FE/TypeScript

[TypeChallenges] 7. Readonly (easy)

채린씨 2023. 3. 24. 22:41

문제

Implement the built-in Readonly<T> generic without using it.

Constructs a type with all properties of T set to readonly, meaning the properties of the constructed type cannot be reassigned.

 

For example:

interface Todo {
  title: string
  description: string
}

const todo: MyReadonly<Todo> = {
  title: "Hey",
  description: "foobar"
}

todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property

(출처: https://github.com/type-challenges/type-challenges/blob/main/questions/00007-easy-readonly/README.md)

 


나의 풀이

TypeScript의 내장 유틸리티 타입인 Readonly를 직접 구현하는 문제였다!

Readonly는 모든 프로퍼티가 읽기 전용으로 설정된 타입을 생성하므로 readonly 키워드를 이용해서 모든 프로퍼티를 읽기 전용으로 설정했다.

type MyReadonly<T> = {
  readonly [Key in keyof T]: T[Key]
}

 


참고자료

1. 제네릭이란?

https://joshua1988.github.io/ts/guide/generics.html

 

제네릭 | 타입스크립트 핸드북

제네릭(Generics)의 사전적 정의 제네릭은 C#, Java 등의 언어에서 재사용성이 높은 컴포넌트를 만들 때 자주 활용되는 특징입니다. 특히, 한가지 타입보다 여러 가지 타입에서 동작하는 컴포넌트를

joshua1988.github.io

 

2. Readonly란?

https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype

 

Documentation - Utility Types

Types which are globally included in TypeScript

www.typescriptlang.org

 

2. readonly 키워드

https://www.typescriptlang.org/docs/handbook/2/objects.html#readonly-properties

 

Documentation - Object Types

How TypeScript describes the shapes of JavaScript objects.

www.typescriptlang.org

 

'FE > TypeScript' 카테고리의 다른 글

[TypeChallenges] 4. Pick (easy)  (0) 2023.03.24
[TypeChallenges] 13. Hello World (warm-up)  (0) 2023.03.24
Comments