#Declare a key that "starts with" something?
1 messages · Page 1 of 1 (latest)
Preview:ts interface skills { acr: "Acrobatics" apr: "Appraise" art: "Artistry" blf: "Bluff" clm: "Climb" crf: "Craft" [`crf.${string}`]: "this doesn't work" }
You were very close: [k: `crf.${string}`]:
Ah, right, thanks! With that change, I've got other code that doesn't work now
Preview:```ts
declare type SkillId = keyof skills
type skills = {
acr: "Acrobatics"
apr: "Appraise"
//.. plus lots more that aren't necessary for the example
// handleSkills below now doesn't work
[key: crf.${string}]: string // commenting this out now lets handleSkills wor
...```
@cyan horizon
try
const handleSkills = (skill: Record<string, string | undefined>) => console.log(skill);
Well, this works, but why? That's not actually a correct definition for how I want to use it. I.e. if I pass along { acr: undefined } that will pass the type constraint but is incorrect.
(or more generically, handleSkills({ foo: undefined });)
Ideally, the goal is to type the [key: 'crf.${string}']: string line so that it still works without having to re-type getSkills or handleSkills (especially not handle skills, because I want it to be generic enough to handle things that are as strongly typed as skill ids)
(and handleSkills may have just been a poor name for this example since it does handle more than just skills)
Preview:ts ... const getSkills = () => ({ acr: 'Acrobatics', }) satisfies Partial<Record<SkillId, string>>; ...
Partial is defined as type Partial<T> = { [P in keyof T]?: T[P] | undefined; }
which means both optional key and optional value (undefined)
now getSkills returns { acr: string; } (optional keys only, values can't be undefined)
which is assignable to Record<string, string>
something like this works around the fact that the index signature still allows undefined: