0

In TypeScript I can do the following:

const fetchUrl = async () => {
  let url: URL = new URL("http://example.com")
  url.searchParams.set("q", "hello")
  url.searchParams.set("a", "world!")
  return fetch(url)
}

And I want to know why this is accepted because the signature of fetch accepts a Union Type of RequestInfo = string | URLLike | Request as the first parameter. I assume that the URL-Type matches URLLike which is just an interface

interface URLLike {
    href: string;
}

But since URL is not extending from URLLike it seems odd for me that it should match. Is this about the href variable that exist in both types?

2
  • 1
    Does this answer your question? Why duck typing is allowed for classes in TypeScript Commented Feb 5, 2021 at 10:44
  • I was not aware of what 'duck typing' means which is why I was not able to find an answer to my question. Tank! Nevertheless my question might be worth of beeing found since it phrases the question in another way. Commented Feb 5, 2021 at 13:52

1 Answer 1

1

TypeScript uses structural typing rather than nominal typing. What this means is that only the shape matters. URLLike is defined as a shape with a href property of type string so absolutely any type that has a href property of type string will do.

Other languages such as Java are nominally typed and here the name matters. So only types that explicitly said they implement URLLike would be valid.

You can think about this a bit like compile-time duck typing.

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.