ts怎么将一个type里面的所有属性变为必选?

export type configType = {
  projectName: string,

  template: string,

  dirAlias?: {
    base?: string,
    options?: string,
    ejs?: string
  },

  ejsVarAilas?: string,

  options?: Array<string>
}

type b = Required<configType>

上面使用Required只能让第一层变为必选,我想让dirAlias下面的属性也变为必选需要怎么做

解答:

export type DeepRequired<T> = {
  [K in keyof T]: Required<DeepRequired<T[K]>>
}

export type configTypeDeepRequired = Required<DeepRequired<configType>>

export type configType = {
  // 项目名
  projectName: string

  // 模板名
  template: string

  // 模板详细文件夹别名
  dirAlias?: {
    // 基础文件夹
    base?: string
    // 选项文件夹
    options?: string
    // ejs模板文件夹
    ejs?: string
  }

  // ejs值的别名
  ejsVarAilas?: string

  // 选项文件夹名列表
  options?: Array<string>
}
阅读 2.2k
1 个回答
export type DeepRequired<T> = {
  [K in keyof T]: Required<DeepRequired<T[K]>>
}

export type configType = {
  projectName: string,

  template: string,

  dirAlias?: {
    base?: string,
    options?: string,
    ejs?: string
  },

  ejsVarAilas?: string,

  options?: Array<string>
}

type b = DeepRequired<configType>

https://www.typescriptlang.or...

logo
Microsoft
子站问答
访问
宣传栏