When you define a type, it simply describes the type of a function without actually implementing any functionality. Therefore, you cannot use it directly to convert a string to a Person | undefined
because it doesn't perform any action; it only indicates what should happen if a function is created. Types do not exist at runtime (except for enums which have some presence). A type itself cannot perform value conversion, although types can convert other types.
To achieve the desired conversion from a string to either a Person
or undefined
, you will need to create a function that handles this task. Here's an example:
const findPerson: FindPerson = (personId: string) => {
// ...implementation code...
};
The following snippet provides context with placeholder and stand-in code:
// Placeholder
type Person = {
id: string;
name: string;
}
// Your type
/*export*/ type FindPerson = (personId: string) => Person | undefined;
// Stand-in data storage for persons
const personStore: Map<string, Person> = new Map();
function addPerson(id: string, name: string) {
personStore.set(id, {id, name});
}
addPerson("1923-01-01a", "Joe Bloggs");
addPerson("1924-01-01b", "Mohammed bin Ammar");
addPerson("1925-01-01c", "Constanza Alvares");
// Defining the actual function
const findPerson: FindPerson = (personId: string) => {
return personStore.get(personId);
};
// Example usage
const person = findPerson("1923-01-01a");
console.log(person);
console.log(findPerson("1924-01-01b"));
console.log(findPerson("no-such-person"));
Playground link
A type like FindPerson
proves most useful when:
You want to prevent coding errors during maintenance, such as adding incorrect parameters or altering the function's behavior incorrectly. This is especially helpful when multiple functions share the same interface.
You already have a function, but the parameter names are unclear and could benefit from renaming. For instance, using findPerson
like this:
const findPerson: FindPerson = personStore.get.bind(personStore);
Without the type annotation, the parameter hint would be "key" inherited from the type of Map.prototype.get
. With the type annotation, it becomes more specific as "personId."