[英]Create a type with the same nested keys as another type but all values are string
[英]Use type of values and make another object in the same structure but with string as values and also deep nesting
假設我們有一個這樣的 TypeScript 類型:
type FormValues = {
name: string
organization: {
name: string
telephone: string
employees: number
}
}
基於這種類型,我想要一個 TypeScript 實用程序,它會產生以下類型:
type ErrorValues = {
name?: string
organization?: {
name?: string
telephone?: string
employees?: string
}
}
所以我可以有這樣的事情:
const errors: ErrorUtility<FormValues>
console.log({ employeesError: errors?.organization.employees })
type ErrorUtility<T> = {
[K in keyof T]?: T[K] extends number | string | boolean ? string : ErrorUtility<T[K]>;
}
這說的是:
對於輸入類型
T
中的任何鍵K
,結果類型中有一個鍵K
,因此該值是可選的,並且:
- 一個字符串,在原始值類型的情況下; 或者
- 本身是一個錯誤對象,遞歸地。
這是一個顯示它正在使用的操場: https : //tsplay.dev/wXk3LW
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.