Make writing a habit together! This is the second day of my participation in the “Gold Digging Day New Plan · April More text challenge”. Click here for more details.
Dear, hello, everyone. I am “Front-end Xiaoxin”. 😇 has been engaged in front-end development and Android development for a long time
Knowledge application:
- What is readOnly and what is the difference between a constant?
- Indexed Access Types: Indexed Access Types;
- Keyof type operator;
- Mapped Types;
Analysis of the topic:
Subject Address:7-easy-readonly As shown in the figure, we need to design a generic type utility, MyReadonly, that takes the incoming Todo interface and iterates through each property to read but not edit, and returns the type structure that functions as Readonly.
Answer:
Test cases:
- The test case is simple, comparing the results of our implemented type tool with those of the built-in Readonly type tool.
- We can also declare a variable and constrain it to the type returned by the type tool we implement, reassign it and see if it succeeds.
/* _____________ Test case _____________ */
// Complete test cases can be seen in the Type-challenges project. Click on the title link to go to
import { 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}}Copy the code
Answer:
The goal is to add a ReadOnly attribute to each attribute of the incoming interface
- The result returned is always represented by an object
- Readonly key: value, key refers to the Todo attribute, value refers to the type of the Todo attribute
- How to obtain value: by index type access T[key] form
- How to iterate through each attribute of an interface type by mapping the type keyword in, in the form of [key in type string collection]
- How to get a set of type strings for each attribute of the interface: using keyof
/* _____________ answer _____________ */
type MyReadonly<T> = {
readonly [key in keyof T]: T[key]
}
Copy the code
Test your answers on the drill ground
The next problem is: [type challenge] tuple to object, difficulty ⭐️
Recommended: GFE front end team, welcome everyone XD likes, comments, follow ~
Welcome to follow my public account “Front-end Xiaoxin students”, the first time to push original technical articles.