#javascript #angularjs #reactjs #typescript #redux
#javascript #angularjs #reactjs #typescript #redux
Вопрос:
Как я могу определить ключи: a, b, c, bar
как неопределенный / нулевой / необязательный тип, если foo равно false ? Другими словами, мне нужно, чтобы эти свойства были обязательными, только если foo имеет значение true .
interface ObjectType {
foo: boolean;
a: number;
y: string;
c: boolean;
bar?: { x: number; y: string; z: boolean };
}
Спасибо! 🙂
Ответ №1:
Я думаю, что самый простой способ — просто использовать типы объединения.
interface RequiredObjectType {
foo: true;
a: number;
y: string;
c: boolean;
bar: { x: number; y: string; z: boolean };
}
interface OptionalObjectType {
foo: false;
a?: number;
y?: string;
c?: boolean;
bar?: { x: number; y: string; z: boolean };
}
type AnyObjectType = RequiredObjectType| OptionalObjectType;
Конечно, вы могли бы абстрагировать повторяющиеся свойства, если это необходимо, чтобы сэкономить ввод на типах, которые будут меняться со временем.
interface ObjectTypeValues {
a: number;
y: string;
c: boolean;
bar: { x: number; y: string; z: boolean };
}
interface RequiredObjectType extends ObjectTypeValues {
foo: true
}
interface OptionalObjectType extends Partial<ObjectTypeValues> {
foo: false
}
type AnyObjectType = RequiredObjectType | OptionalObjectType;
Вы также получите вывод типа бесплатно.
if (type.foo) {
// im the required type!
// type.a would be boolean.
} else {
// im the optional type.
// type.a would be boolean?
}