Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: IsStringLiteral #541

Closed
Ayc0 opened this issue Jan 12, 2023 · 5 comments · Fixed by #563
Closed

Feature request: IsStringLiteral #541

Ayc0 opened this issue Jan 12, 2023 · 5 comments · Fixed by #563
Labels
help wanted Extra attention is needed type addition

Comments

@Ayc0
Copy link

Ayc0 commented Jan 12, 2023

What do you think of adding a type that can say if a string is a string literal (like 'foo/bar') and not a regular string?

export type IsStringLiteral<T> = string extends T ? false : true;
@sindresorhus
Copy link
Owner

What are some real-world use-cases for it?

@Ayc0
Copy link
Author

Ayc0 commented Jan 16, 2023

In one of my projects, I'm using a library like react-router, and I only allow it to use literal strings for the path variable. This allows me to use a custom TS type to parse the path and propose the route parameters (like /foo/:bar/:paz) as props in the Route component.

I already have this type util in my project, but I was wondering if other people in the community wanted to use it too.

If you find it useful, feel free to add it to this awesome project!

@tommy-mitchell
Copy link
Contributor

In tsd, expectDocCommentIncludes expects a generic string literal type parameter, but checks for it through the TypeScript compiler. This type could help users when testing.


Related, a better way to write this type would be:

type IsStringLiteral<T> =
  T extends string
    ? string extends T
      ? false
      : true
    : false;

Would adding types to check for other literals be useful? E.g. IsNumericLiteral, etc. Perhaps:

import type {Primitive} from 'type-fest';

type IsLiteral<T extends Primitive> =
  | IsStringLiteral<T>
  | IsNumericLiteral<T>
  | IsBooleanLiteral<T>
  | IsSymbolLiteral<T>
  // ...

I'd be open to adding a PR. Other use cases of IsStringLiteral or other IsXLiteral types would be helpful.

@sindresorhus
Copy link
Owner

Would adding types to check for other literals be useful?

👍 It would make sense to do these too for completeness.

@sindresorhus
Copy link
Owner

This is now accepted. Pull request welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed type addition
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants