[Typescript] Exercise: Template literals for generic

const interValueFromColor = <N extends string, C extends string, T extends number>(colorTag: `${N}-${C}-${T}`) => {
    const [namespace, color, tone] = colorTag.split("-");
    return {
        namespace: namespace as N,
        color: color as C,
        tone: Number(tone) as T
    }
}
const example = interValueFromColor('bg-red-400')

Another approach:

type InterValueFromColor<Color extends string> = Color extends `${infer N}-${infer C}-${infer T}` ? {namespace: N, color: C, tone: T}: never
type Example = InterValueFromColor<'bg-red-400'>

posted @ 2024-01-22 03:08  Zhentiw  阅读(8)  评论(0编辑  收藏  举报