danvk / effective-typescript

Effective TypeScript 2nd Edition: 83 Specific Ways to Improve Your TypeScript
https://effectivetypescript.com
Other
1.56k stars 226 forks source link

Item 13: How NamedVariable can be useful? #38

Closed kimamula closed 1 month ago

kimamula commented 4 months ago

Hi Dan, thank you for the great book!

In Item 13, the NamedVariable type is used as an example to explain how extending union types can be useful. But I don't get it. Could you show me some concrete use cases in which this type is useful? Thanks in advance!

danvk commented 1 month ago

Hey @kimamula, sorry for the slow response. Here's the full snippet:

type Input = { /* ... */ };
type Output = { /* ... */ };
interface VariableMap {
  [name: string]: Input | Output;
}

type NamedVariable = (Input | Output) & { name: string };

This came pretty directly from a use case at my work. We had a tool that worked with CSV data. There were two types of data, inputs and outputs. Internally we removed the name column and constructed that VariableMap. But to output CSV again, we needed to add the name column back.

Hopefully that makes a little more sense. Perhaps not the most useful or widely applicable technique. But hey, the book only claimed that it "can sometimes be useful." :)

kimamula commented 1 month ago

Thank you for the explanation! Yes, that makes sense.