抱歉,标题太复杂了.
我在Typescript 中有这个:
type EthereumAddress = `0x${string}`
type Chain = 'eth'
type ApiMethods = {
getToken(args: {
tokenAddress: EthereumAddress
}): string
getRank(args: {
tokenAddress: EthereumAddress
}): string
}
type ApiPaths<M extends ApiMethods> = {
[K in keyof M]: {
path: string
chain?: Chain
}
}
const apiPaths = {
getToken: {
path: 'tokens/',
chain: 'eth'
},
getRank: {
path: 'rank/',
}
} as const satisfies ApiPaths<ApiMethods>
我想构造一个Paths
类型,它是api可以采用的所有可能路径的联合.如果apiPaths有一个chain参数,那么路径应该是${path}/${chain}
,如果不是${path}
.
我试着这样做:
type Paths<T extends typeof apiPaths = typeof apiPaths> = {
[K in keyof T]: T[K] extends {chain: Chain}
? `${T[K]['path']}${T[K]['chain']}/`
: `${T[K]['path']}`
}[keyof T]
但我得到了一个错误:
Type 'T[K]["path"]' is not assignable to type 'string | number | bigint | boolean | null | undefined'.ts(2322)
Type '"path"' cannot be used to index type 'T[K]'.
为什么path
不是T[K]
的公认参数,如果所有apiPaths
值都明确提及,特别是如果apiPaths
satisfies ApiPaths<ApiMethods>
?