получаю ошибку с типами в свитче в следующем коде?
Причем если поля и их типы указать ручками, а не сослаться на них в объекты, то ошибка пропадает
const FIELDS = {
TYPE: 'type',
} as const;
const TYPES = {
FIRST: 'first',
SECOND: 'second',
} as const;
type IFirstType = {
[FIELDS.TYPE]: typeof TYPES.FIRST;
};
type ISecondType = {
[FIELDS.TYPE]: typeof TYPES.SECOND;
}
type IMainType = IFirstType | ISecondType;
function handleFirstType(data: IFirstType) {}
function handleSecondType(data: ISecondType) {}
function handleMessage(data: IMainType) {
switch (data[FIELDS.TYPE]) {
case TYPES.FIRST: {
handleFirstType(data);
break;
}
case TYPES.SECOND: {
handleSecondType(data);
break;
}
}
}
Argument of type 'IMainType' is not assignable to parameter of type 'IFirstType'.
Type 'ISecondType' is not assignable to type 'IFirstType'.
Types of property '[FIELDS.TYPE]' are incompatible.
Type '"second"' is not assignable to type '"first"'
воспользуйся TypeGuard
Не доглядел) А в ts issues не смотрел?
Если честно, то нет. Даже не знаю как этот кейс там отыскать + я начал грешить на себя, так как он мне показался достаточно простым, думал может торможу где-то я
Ты имел ввиду что-то вроде этого? const FIELDS = { TYPE: 'type', } as const; const TYPES = { FIRST: 'first', SECOND: 'second', } as const; type IFirstType = { [FIELDS.TYPE]: typeof TYPES.FIRST; }; type ISecondType = { [FIELDS.TYPE]: typeof TYPES.SECOND; } type IMainType = IFirstType | ISecondType; function handleFirstType(data: IFirstType) {} function handleSecondType(data: ISecondType) {} function getIsFirstType(data: IMainType): data is IFirstType { return data.type === TYPES.FIRST; } function handleMessage(data: IMainType) { if (getIsFirstType(data)) { handleFirstType(data); return; } handleSecondType(data); }
Заработало, спасибо! НО все равно непонятно, почему в моем кейсе он не сработал, ведт union был достаточно простой, чтобы его сузить “налету”. Видимо у typescript с этим проблема
Обсуждают сегодня