채린씨의 티스토리
[TypeChallenges] 7. Readonly (easy) 본문
문제
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
2. Readonly란?
https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype
2. readonly 키워드
https://www.typescriptlang.org/docs/handbook/2/objects.html#readonly-properties
'FE > TypeScript' 카테고리의 다른 글
[TypeChallenges] 4. Pick (easy) (0) | 2023.03.24 |
---|---|
[TypeChallenges] 13. Hello World (warm-up) (0) | 2023.03.24 |
Comments