Being a beginner in TypeScript and currently learning about enums, I encountered an error with the following example code that I cannot seem to understand. Here's the code snippet:
enum Status {
SUCCESS = 'success',
FAILED = 'failed'
}
interface ResponseSuccess {
databaseId: number
sum: number
from: number
to: number
}
interface ResponseFail {
errorMessage: string
errorCode: number
}
interface GoodResponse {
status: Status.SUCCESS
data: ResponseSuccess
}
interface BadResponse {
status: Status.FAILED
data: ResponseFail
}
let data: GoodResponse = {
"status": 'success', // The error message says: Type '"success"' is not assignable to type 'Status.SUCCESS'.ts(2322)
"data": {
"databaseId": 567,
"sum": 10000,
"from": 2,
"to": 4
}
}
let data2: BadResponse = {
'status': "failed", // Same error here
"data": {
"errorMessage": "Error",
"errorCode": 4
}
}
I found a workaround using objects to define my types and it worked perfectly:
const Status = {
success: 'success',
failed: 'failed',
} as const
export type StatusType = keyof typeof Status
However, I prefer to have the option to select between "good" and "bad" status types.