Reputation: 14796
I want to create a re-usable type for functions, so that I can say:
type MyFunc = ...
const func1: MyFunc = ...
const func2: MyFunc = ...
The following doesn't work, but basically I want:
type Book = {
id: string;
title: string;
}
type createBook = (book: Partial<Book>) => Book;
const someBookFactory: createBook = ({ title }) => ({ id: /* autogenerated */, title });
const someOtherBookFactory: createBook = ({ id, title }) => ({ id, title });
Is this possible in TypeScript?
Upvotes: 0
Views: 423
Reputation: 11558
type createBook = (book: Partial<Book>) => Book;
function getId(): string {
return Math.random().toString();
}
// Partial means they can be undefined so you need to provide default values
const someBookFactory: createBook = ({ title = "untitled" }) => ({ id: getId(), title });
const someOtherBookFactory: createBook = ({ id = getId(), title = "untitled" }) => ({ id, title });
Bottom line is Book is a contract with 2 required fields and if you are not passing them all in, at some point before returning you are in breach of contract. That is the case in all languages with static types.
// You can also have both fallbacks handled inside
const anotherBookFactory: createBook = ({ id, title }) => {
return {
id: id ?? getId(),
title: title ?? "untitled"
};
};
Upvotes: 1