LearningTypeScript / site

Companion website for the Learning TypeScript book.
https://learningtypescript.com
MIT License
48 stars 12 forks source link

✨ Feature: form for asking questions concerning the book #56

Closed puffy-puffy closed 2 years ago

puffy-puffy commented 2 years ago

Feature Request Checklist

Feature

submitting questions concerning a topic in the book via a form or something like that

Additional Info

Don't know if its allowed to ask this here but I just started to read your book, really helpful stuff but I am kinda lost on a particular term.... "signature". Simply what are signatures in typescript? I do know the call, construct and index signatures (ie their syntax their use cases) but I am still confused on the "signature" term. To further clarify my question is there a catch all phrase to explain what a signature is in typescript. I asked this on stackoverflow and the answer was '"signature" is used in TypeScript to mean an entry in an object-like type surrounded by curly braces (but usually not referring to plain properties.) If I have an interface Foo { bar: string; [k: string]: unknown; baz(): void; (x: string): number; new (y: string): Date } then Foo has a bar property, and a string index signature, and a baz method signature, and a call signature, and a construct signature."' Does that make sense🤔?

JoshuaKGoldberg commented 2 years ago

Hey @puffy-puffy, thanks for asking (and for reading the book)! This is a great question and while this repo probably isn't the best place to ask it, I'm happy to answer here for now 😄. In the future my bet is the best place to ask would probably be the TypeScript Discord or tagging me on Twitter.

what are signatures in typescript?

I think what you're looking for is what Learning TypeScript lists in its glossary under the definition of a call signature:

Type system description of how a function may be called. Includes a list of parameters and a return type.

In other words, a signature is the type system's way of describing how you're supposed to call a function.

entry in an object-like type surrounded by curly braces

That's one way to declare a signature, yes. Here's an object that says it can take in a single parameter of type string and return a number:

interface StringToNumber {
  (input: string): number;
}

Another way of saying that would be with a direct type alias:

type StringToNumber = (input: string) => number;

Roughly, both of those syntaxes say values that are the type StringToNumber have that one signature. So if you have a variable that's (either) type StringToNumber, TypeScript will know you can call it like that.

let myFunction: StringToNumber;

// Type of input: string
myFunction = (input) => input.length; // Ok

Is that the info you're looking for?

Edit: oh, and yes, what you're saying makes sense and seems right to me. There are different kinds of signatures, and call signatures just happen to be the most common.