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

Question: How to type "a color"? #58

Open
escapedcat opened this issue Oct 21, 2023 · 2 comments
Open

Question: How to type "a color"? #58

escapedcat opened this issue Oct 21, 2023 · 2 comments

Comments

@escapedcat
Copy link

This is just running fine:

const DEFAULT_COLORS: [string, string, string] = ['white', 'yellow', 'red'];
console.log(pc[DEFAULT_COLORS[1]]('sad'));

https://codesandbox.io/p/sandbox/picocolors-types-29zfg9?file=%2Fsrc%2Findex.ts%3A11%2C1

But how to type this correct? I'm too stupid, sorry.
For DEFAULT_COLORS[1]
I get this:

// Element implicitly has an 'any' type because expression of
// type 'string' can't be used to indextype
// 'Colors & { createColors: (enabled?: boolean | undefined) => Colors; }'.
//  No index signature with a parameter of type 'string' was
// found on type 'Colors & { createColors: (enabled?: boolean | undefined) => Colors; }'.

Problem is that a user can just overwrite colors by using own colors handed in as strings. So I'm trying to stick to that.

@alexeyraspopov
Copy link
Owner

You can define a Color type as a key of the package object

import pc from "picocolors";

type Color = keyof typeof pc;

const DEFAULT_COLORS: [Color, Color, Color] = ["white", "yellow", "red"];

@escapedcat
Copy link
Author

Thanks for your reply!
Unfortunately with this I get an error and no more output:

This expression is not callable.
  Not all constituents of type 'boolean | Formatter | ((enabled?: boolean) => Colors)' are callable.
    Type 'false' has no call signatures.typescript(2349)
const DEFAULT_COLORS: [keyof Colors | "createColors", keyof Colors | "createColors", keyof Colors | "createColors"]

Update the sandbox:
https://codesandbox.io/p/sandbox/picocolors-types-29zfg9?file=%2Fsrc%2Findex.ts%3A7%2C1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants