'Typescript differentiate between string types
I would like to know if it is somehow possible to distinguish between two strings.
The concrete use case is this:
I am trying to typecast an API which returns different strings for the user in different places. Some interfaces return the ID (string), some return the first name, some return the active directory name, and some return the full name:
Examples:
// books
{
id: "1",
creator: "Peter Pan" // refers to the same user
}
// films
{
id: "1",
creator: "peterpahn" // refers to the same user
}
Now I would like to type the different responses so that I can distinguish between "FirstName", "IdName", "FullName" to have type safety when processing this data.
I can imagine that one solution could be to use an object with different optional parameters instead of a string, but in that case I would have to map each return value, which I wanted to avoid, because it seems to be more complex than it needs to be.
What I was hoping for would be something like this:
type UserId = string
type UserFirstName = string;
function showUserName(user: UserId) {
console.log(`Name: ${user}`);
}
showUserName("Test" as UserId);
showUserName("Test" as UserFirstName); // this should throw a type error
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
