0

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?

1 Answer 1

1
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"
  };
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.