TS2322: Type 'string' is not assignable to type 'DeviceType'.
interface IDeviceItem {
smartphoneName?: string;
deviceStatus: boolean;
deviceType: DeviceType;
location: string;
lastSeen?: string;
}
enum DeviceType {
smartphone = 'smartphone',
computer = 'computer'
}
<DeviceItem deviceType={item.deviceType} />
TS2322: Type 'string' is not assignable to type 'DeviceType'.
deviceType: 'smartphone',
<img src={`/icon/device-${deviceType}-icon.svg`} />
item.deviceType
у тебя строка, а не DeviceType
. Проверь что у тебя там в item
. const deviceType = [
{
smartphoneName: 'Precision 5530',
deviceType: 'smartphone',
},
{
smartphoneName: 'MS-7A34',
deviceType: 'computer',
},
{
smartphoneName: 'MS-7A34',
deviceType: 'computer',
},
]
{deviceType .map((item, index) => (
<DeviceItem
key={`${item}_${index}`}
smartphoneName={item.smartphoneName}
deviceType={item.deviceType}
/>
))}
export enum DeviceType ...
import { DeviceType } from ...
Мне бы как-то только строку получать
Array<{
smartphoneName: string;
deviceType: DeviceType;
}>
any
. const deviceType = [
{
smartphoneName: 'Precision 5530',
deviceType: 'smartphone',
},
{
smartphoneName: 'MS-7A34',
deviceType: 'computer',
},
{
smartphoneName: 'MS-7A34',
deviceType: 'computer',
},
] as Array<{
smartphoneName: string;
deviceType: DeviceType;
}>
interface IDeviceResponseItem {
smartphoneName: string;
deviceType: DeviceType;
}
function isDeviceResponseItem(item: unknown): item is IDeviceResponseItem {
if (!item)
return false;
const { smartphoneName, deviceType } = item as IDeviceResponseItem;
if (typeof smartphoneName === 'string' && deviceType in DeviceType)
return true;
return false;
}
function getResponse(): IDeviceResponseItem[] {
// ответ от сервера неизвестного типа
const json: unknown = [
{
smartphoneName: 'Precision 5530',
deviceType: 'smartphone',
},
{
smartphoneName: 'MS-7A34',
deviceType: 'computer',
},
{
smartphoneName: 'MS-7A34',
deviceType: 'computer',
},
];
// проверка что ответ именно тот который нужен
if(!Array.isArray(json) || !json.every(isDeviceResponseItem))
throw new Error('[wrong response]');
return json;
}
const deviceType = getResponse();
<img src={`/icon/device-${deviceType}-icon.svg`} alt={smartphoneName} />