-
-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
33 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,22 @@ | ||
export type Props<T> = T extends `${string}{${infer U}}${infer Rest}` | ||
? { [K in U]: unknown } & Props<Rest> | ||
: Record<string, unknown>; | ||
type Evaluate<T> = T extends infer O ? { [K in keyof O]: O[K] } : never; | ||
|
||
export type Props<T> = Evaluate< | ||
T extends `${string}{${infer U extends string}}${infer Rest extends string}` | ||
? { [K in U]: unknown } & Props<Rest> | ||
: unknown | ||
>; | ||
|
||
export function interpolate<const T extends string, O extends Props<T>>( | ||
event: T, | ||
props: O, | ||
to_string: (v: keyof O) => string = String, | ||
to_string: (v: O[keyof O], key: keyof O) => string = String, | ||
): string { | ||
return event.replaceAll(/\{([^}]+)\}/g, (_, key) => { | ||
if (!hasOwn(props, key)) return `{${key}}`; | ||
return to_string(props[key] as keyof O); | ||
return to_string(props[key], key); | ||
}); | ||
} | ||
|
||
function hasOwn(obj: unknown, key: string) { | ||
function hasOwn<T extends Record<string, unknown>>(obj: T, key: PropertyKey): key is keyof T { | ||
return Object.prototype.hasOwnProperty.call(obj, key); | ||
} |