I am exploring different types of employees:
interface Employee {
employeeType: string
}
interface Manager extends Employee { employeeType: 'MANAGER' // .. etc }
interface Developer extends Employee { employeeType: 'DEVELOPER' // .. etc }
type Staff = Developer | Manager
In order to create a new type that contains all possible string literals for Staff > employeeType
, allowing for dynamic updates when new employee types are added:
Here is an example of how it could be manually defined and used:
type EmployeeType = 'DEVELOPER' | 'MANAGER'
The goal is to have the EmployeeType
automatically update when a new type of Employee
interface is added to the Staff
union, like this:
...
interface Designer extends Employee { employeeType: 'DESIGNER' // ..etc }
type Staff = Developer | Manager | Designer
// ... now EmployeeType contains 'DEVELOPER' | 'MANAGER' | 'DESIGNER'
This approach allows for strong type checking in scenarios such as:
function createEmployee(employeeType: EmployeeType, attributes: ...) {
// ...
}
Instead of using employeeType: string
which lacks type safety.
Is there a way to achieve this in TypeScript? Check out this Typescript Playground :)
A related question (using Enum
s):