Type A is not assignable to type A & B & C. Not sure why ts infers with an `&` and not `|`

TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
1 Reply
Alky
Alky10mo ago
To be honest, i don't know exactly what you're trying to do, but i made what i think you want to do. See:
type ApiResponse<T extends string> = {
[key in T]: string
} & {
[key: string]: string
}

type APIERRORCODES3<T extends string> =
| {
[key: string]: {
[key: number]: {
i18nKey: T
values?: (payload: ApiResponse<T>) => { [key in T]: string }
}
}
}
| {
[key: string]: string
}

const someFun2 = <T extends string>(path: string) => {
let _payload: ApiResponse<T> | undefined
const codes2: APIERRORCODES3<T> = {}

const codesKey = Object.keys(codes2).find((k) => RegExp(k).test(path)) as keyof APIERRORCODES3<T> | undefined // unsure why it cant infer this

const _code = codesKey && codes2[codesKey]

if (_payload && _code && typeof _code === 'object') {
const _value = _code[100].values && _code[100].values(_payload)
return _value
} else {
return undefined
}
}

const test = someFun2<'A'>('/A')
type ApiResponse<T extends string> = {
[key in T]: string
} & {
[key: string]: string
}

type APIERRORCODES3<T extends string> =
| {
[key: string]: {
[key: number]: {
i18nKey: T
values?: (payload: ApiResponse<T>) => { [key in T]: string }
}
}
}
| {
[key: string]: string
}

const someFun2 = <T extends string>(path: string) => {
let _payload: ApiResponse<T> | undefined
const codes2: APIERRORCODES3<T> = {}

const codesKey = Object.keys(codes2).find((k) => RegExp(k).test(path)) as keyof APIERRORCODES3<T> | undefined // unsure why it cant infer this

const _code = codesKey && codes2[codesKey]

if (_payload && _code && typeof _code === 'object') {
const _value = _code[100].values && _code[100].values(_payload)
return _value
} else {
return undefined
}
}

const test = someFun2<'A'>('/A')
Since yours payloads appears to always be an object with different keys, I've made an generic ApiResponse<T> that pass T as an obligatory key. Since i also imagine that your api errors will have a default format, I've created APIERRORCODES3<T extends string> that receives it's format but needs a check to be sure that it's correct(i'm guessing it will be received externally). Also, you change it to be the preferred object or undefined instead of what i did. I just did it this way so i can declare it as a variable {} to test the function typing. When getting it from a request, you can change for what bests suits you. Make some runtime type checking, and it returns the payload with the key passed as a generic. If i'm missing something or you need more help, just let me know.
No description
Want results from more Discord servers?
Add your server