Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Preface:

This is the fourth installment of TS. If you want to get TS from scratch, please start from the first installment juejin.cn/post/701033…

The first question

Define an EmptyObject type using a type alias such that only EmptyObject assignments are allowed

Type EmptyObject = {} // Test case const shouldPass: EmptyObject = {}; Const shouldFail: EmptyObject = {const shouldFail: EmptyObject = {prop: "TS"}Copy the code

Define a type definition of a takeSomeTypeOnly function using a type alias so that its arguments are allowed only strictly for values of type SomeType. An example is as follows

Type SomeType = {prop: string} function takeSomeTypeOnly(x: SomeType = {prop: string} SomeType) {return x} // Const x = {prop: 'a'}; TakeSomeTypeOnly (x) // Const y = {prop: 'a', addditionalProp: 'x'}; TakeSomeTypeOnly (y) // compilation errors will occurCopy the code

The content of this question

Application of never. If a type is assigned to never, it will not accept any assignment, thus limiting the parameters.

Answer key EmptyObject

type EmptyObject = { // type PropertyKey = string | number | symbol [K in PropertyKey]: // Test case const shouldPass: EmptyObject = {}; Const shouldFail: EmptyObject = {const shouldFail: EmptyObject = {prop: "TS"}Copy the code

If an attribute is of type never, it cannot be assigned. If an attribute is of type never, it cannot have an attribute. If an attribute is of type never, it cannot have an attribute.

Answer key takeSomeTypeOnly

Answer:

  1. Type SomeType = never; type SomeType = never
type SomeType = { prop: string } type Exclusive<T1, T2 extends T1> = { [K in keyof T2]: K extends keyof T1 ? Function takeSomeTypeOnly<T extends SomeType>(x: Exclusive<SomeType, T>) {return x} const x = {prop: 'a'}; TakeSomeTypeOnly (x) // Const y = {prop: 'a', addditionalProp: 'x'}; TakeSomeTypeOnly (y) // compilation errors will occurCopy the code

Pass (SomeType); set never to pass (SomeType);

The second question

Defines the NonEmptyArray utility type used to ensure that data is not an empty array.

Type NonEmptyArray<T> = // Your implementation code const a: NonEmptyArray<string> = [] NonEmptyArray<string> = ['Hello TS'] // Non-empty data, normal useCopy the code

Investigate knowledge points

How do I get the first item of an array and assign it a type

Answer key 1

type NonEmptyArray<T> = [T, ...T[]]
Copy the code

Define the first item of the array to be of type T, or undifind if it is empty

Answer key 2

type NonEmptyArray<T> = T[] & { 0: T };
Copy the code

Using the cross type, the type whose cross result is index 0 is T, with the same purpose as the first result