Skip to content

Instantly share code, notes, and snippets.

@shirakaba
Created May 14, 2021 13:53
Show Gist options
  • Save shirakaba/776cb73bebf7d5d4bca31acc0cbfe139 to your computer and use it in GitHub Desktop.
Save shirakaba/776cb73bebf7d5d4bca31acc0cbfe139 to your computer and use it in GitHub Desktop.
TypeScript guard function for type-checking records by index signatures
type Check<T> = {
[K in keyof T]: K extends `dull.${string}`
? T[K] extends string
? T[K]
: never
: K extends `rich.${string}`
? T[K]
: never
}
function isRichAndDull<T extends Record<string, any>>(value: Check<T>): Check<T> {
return value
}
const config = isRichAndDull({
"dull.foo": "hello",
"rich.foo": new Date(),
})
@shirakaba
Copy link
Author

shirakaba commented May 14, 2021

What I'm ultimately aiming for, though, is something like this:

const config: RichAndDullConfig = {
    "dull.foo": "hello",
    "rich.foo": new Date(),
}

interface RichAndDullConfig {
    // Dull keys, e.g. "dull.foo" and "dull.bar" may only have string values.
    [dullKey: `dull.${string}`]: string;
    
    // Rich keys, e.g. "rich.foo" and "rich.bar" may have any value.
    [richKey: `rich.${string}`]: any;
}

... However, it fails with: An index signature parameter type must be either 'string' or 'number'. in TypeScript 4.3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment