簡體   English   中英

將對象屬性約束為具有在 TypeScript 中的鍵必須相同的屬性的對象

[英]Constrain objec properties to be object with properties whose keys must be the same in TypeScript

我正在創建一個截面形式。 每個部分都必須具有初始值和驗證模式。 為了幫助團隊以一致的方式發展,我想確保每個section看起來像這樣:

interface Section {
  initialValues: { [key: string]: any };
  validationSchema: { [key: string]: Yup.AnySchema };
}

有沒有辦法限制initialValuesvalidationSchema使它們必須包含相同的鍵?

即,這將起作用:

const section1: Section = {
  initialValues: {
    name: "",
    age: undefined // will be a number
  },
  validationSchema: {
    name: Yup.string().required(),
    age: Yup.number().required()
  }
}

而這會破壞:

const section1: Section = {
  initialValues: {
    name: "",
    age: undefined // will be a number
  },
  validationSchema: {
    name: Yup.string().required(),
    height: Yup.number().required() // should error, as height does not exist on initialValues
    // error because we are missing the age property and its validation here
  }
}

有沒有辦法在打字稿中完成這樣的約束,而不必預定義鍵?

在這種情況下,用否定創建獨立類型是不可能的。 為了使其工作,在打字稿中,您通常需要使用函數參數推斷。 參見示例:

import Yup from 'yup'

interface Section<T, U extends T> {
    initialValues: T;
    validationSchema: U;
}

const sectionBuilder = <T, U extends T>(section: Section<T, T & U>) => {

}

sectionBuilder({
    initialValues: { name: 'hello' },
    validationSchema: { name: 'john' } // ok
})

sectionBuilder({
    initialValues: { name: 'hello' },
    validationSchema: { age: 42 } // expected error
})

sectionBuilder({
    initialValues: { name: 'hello' },
    validationSchema: { name: 'john', age: 42 } // expected error
})


操場

Section中的 Generic UTU的交集,或者換句話說, UinitialValuesvalidationSchema通用的一組屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM