#Declare a key that "starts with" something?

1 messages · Page 1 of 1 (latest)

cyan horizon
#

I'm trying to make a generic key that requires the first four characters plus any string after that. Can this be done?

hasty turretBOT
#
claudekennilol#0

Preview:ts interface skills { acr: "Acrobatics" apr: "Appraise" art: "Artistry" blf: "Bluff" clm: "Climb" crf: "Craft" [`crf.${string}`]: "this doesn't work" }

sweet jay
#

You were very close: [k: `crf.${string}`]:

cyan horizon
hasty turretBOT
#
claudekennilol#0

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
...```

hollow depot
#

@cyan horizon

try

const handleSkills = (skill: Record<string, string | undefined>) => console.log(skill);
cyan horizon
#

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)

hasty turretBOT
#
jakoxb#0

Preview:ts ... const getSkills = () => ({ acr: 'Acrobatics', }) satisfies Partial<Record<SkillId, string>>; ...

supple niche
#

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: