我试图通过选取特定的对象键值,根据"props 键值"生成"动态对象键值".
假设我通过{ name: 'someEntity', unrelatedKey: 123 }
分,我想返回{ someEntity: 'ok' }
分.如果返回值是typescript类型定义的,那么该怎么做呢?我try 过类似的方法,但不起作用:
type GetExampleProps = {
name: string
unrelatedKey: number
}
type GetExampleRes<T> = {
[key: T]: string
}
function getExample<T extends GetExampleProps> (props: T): GetExampleRes<T['name']> {
return {
[props.name]: 'ok'
}
}
const example = getExample({ name: 'someEntity', unrelatedKey: 123 })
example.someEntity // should be valid type string
example.hello // should be invalid, missing key