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?
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.