Make writing a habit together! This is the sixth 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. Exclude outputs the remaining union types after excluding the characteristic types from the union types
  2. Conditional type application
  3. Application of distributed conditional types

Analysis of the topic:

Subject Address:43-easy-exclude As shown in the figure above, we need to design a type tool consistent with the built-in Exclude function that excludes specified types from known union types and returns the rest.

Answer:

Test cases:

/* _____________ Test case _____________ */
import { Equal, Expect } from '@type-challenges/utils'

type cases = [
    Expect<Equal<MyExclude<"a" | "b" | "c"."a">, Exclude<"a" | "b" | "c"."a">>>,
    Expect<Equal<MyExclude<"a" | "b" | "c"."a" | "b">, Exclude<"a" | "b" | "c"."a" | "b">>>,
    Expect<Equal<MyExclude<string | number | (() = > void), Function>, Exclude<string | number | (() = > void), Function> > >,)Copy the code

答案 :

  1. We need to get excluded Types from a set of union Types, and then we need to use Ts type to program Conditional Types for Conditional Types.
    1. Syntax example: SomeType extends OtherType? TrueType : FalseType;
    2. TrueType is obtained when SomeType can be assigned to OtherType and FalseType is obtained in reverse.
  2. This problem uses distributed condition types in condition types to support union types, such as the document example, which can separate the union types we pass into the corresponding array types and return them to us
    1. type ToArray = Type extends any ? Type[] : never;
    2. type StrArrOrNumArr = ToArray<string | number>;
  3. We return never when the union type in T can assign a type U that needs to be excluded, and return the type otherwise.
/* _____________ answer _____________ */
type MyExclude<T, U> = T extends U ? never : T;
Copy the code

Go to the drill ground and test your answer

【 type challenge 】 the difficulty ⭐️


Welcome to follow my public account “Front-end Xiaoxin students”, the first time to push original technical articles.