typescript 结构部分必填 和 结构部分可选

2022-08-18 15:10  202人阅读  评论 (0)

基础结构

User用户结构

type interface User {
  id: number;
  username: string;
  password?: string;
  nickname?: string;
  age?: numer;
  gender?: number;
}

PartialRequired 结构部分必填

PartialRequired 结构部分必填

type PartialRequired<T, K extends keyof T> = { [E in K]-?: T[E]; } & { [E in Exclude<keyof T, K>]?: T[E]; };

accountInfo 账户登陆

const accountLogin: PartialRequired<User, 'username' | 'password'> = {
  username: 'dotcoo',
  password: '123456',
};

accountInfo ts 结构如下

type interface User {
  id?: number;
  username: string;
  password: string;
  nickname?: string;
  age?: numer;
  gender?: number;
}

PartialOptional 结构部分可选

PartialOptional 结构部分可选

type PartialOptional<T, K extends keyof T> = { [E in K]?: T[E]; } & { [E in Exclude<keyof T, K>]-?: T[E]; };

userInfo 用户信息

const userInfo: PartialOptional<User, 'id' | 'username' | 'password'> = {
  nickname: 'dotcoo',
  age: 26,
  gender: 1,
};

userInfo ts 结构如下

type interface User {
  id?: number;
  username?: string;
  password?: string;
  nickname: string;
  age: numer;
  gender: number;
}





豫ICP备09035262号-1