Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

Why is TypeScript accepting an URL in node-fetch

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?

question from:https://stackoverflow.com/questions/66061772/why-is-typescript-accepting-an-url-in-node-fetch

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...