1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Type Narrowing With Const VS Let Strings as a TypeScript TIL

This commit is contained in:
jbranchaud
2022-09-04 10:30:39 -05:00
parent e5166f2432
commit f4eabeb0a2
2 changed files with 42 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1236 TILs and counting..._
_1237 TILs and counting..._
---
@@ -1142,6 +1142,7 @@ _1236 TILs and counting..._
- [Generate Inferred Type From Zod Schema](typescript/generate-inferred-type-from-zod-schema.md)
- [Interfaces With The Same Name Are Merged](typescript/interfaces-with-the-same-name-are-merged.md)
- [Re-Export An Imported Type](typescript/re-export-an-imported-type.md)
- [Type Narrowing With Const VS Let Strings](typescript/type-narrowing-with-const-vs-let-strings.md)
- [Type Narrowing With Similarly Shaped Objects](typescript/type-narrowing-with-similarly-shaped-objects.md)
- [Type Promise Results With The Awaited Type](typescript/type-promise-results-with-the-awaited-type.md)
- [Use An Array Check For Type Narrowing](typescript/use-an-array-check-for-type-narrowing.md)

View File

@@ -0,0 +1,40 @@
# Type Narrowing With Const VS Let Strings
[TypeScript's `typeof`
operator](https://www.typescriptlang.org/docs/handbook/2/typeof-types.html) can
be used to capture the type of a variable.
For instance, we can use it with a string variable like so:
```typescript
let status = 'active';
type Status = typeof status;
//=> type Status = string;
```
The result is a type `Status` defined as a `string`.
What if we were to do the same with a string variable defined with `const`
(instead of `let`)?
```typescript
const status = 'active';
type Status = typeof status;
//=> type Status = 'active';
```
We get a different result. A much more specific result. The `Status` type
definition in this case isn't just any `string`. TypeScript knows specifically
that it is the string `'active'`.
This is _Type Narrowing_ at work. With our `let` string, which can be redefined
at anytime, the most TypeScript can tell us about it is that it is a `string`.
Our `const` string, on the other hand, is frozen as `'active'`, so TypeScript
can narrow the type from `string` to the string `'active'`.
That can be handy for [defining a union type from existing `const`
values](https://twitter.com/jbrancha/status/1565770454052249601).
[source](https://twitter.com/jbrancha/status/1565752445187358721)