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:

  1. What is readOnly and what is the difference between a constant?
  2. Indexed Access Types: Indexed Access Types;
  3. Keyof type operator;
  4. 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:

  1. The test case is simple, comparing the results of our implemented type tool with those of the built-in Readonly type tool.
  2. 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

  1. The result returned is always represented by an object
  2. Readonly key: value, key refers to the Todo attribute, value refers to the type of the Todo attribute
  3. How to obtain value: by index type access T[key] form
  4. 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]
  5. 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.