【发布时间】:2022-02-03 17:50:35
【问题描述】:
我整天都在为此苦苦挣扎,我是打字稿的新手,并试图在数组中存在特定值时有条件地要求对象属性。
这里是链接生成器。只有 Pinterest 关心图像 URL,所以如果“pinterest”在平台数组中,我想要求它。
type share = 'facebook' | 'pinterest' | 'twitter'
interface shareProps {
pageTitle: string;
platforms: share[];
url: string;
description: string;
}
interface propsWithImage extends shareProps {
image: string;
}
type hasPinterest<T extends any[]> = T extends [infer U, ...infer V]
? U extends 'pinterest'
? propsWithImage
: hasPinterest<V>
: shareProps
function fn <T extends shareProps> (props: hasPinterest<T['platforms']>): string[] {
const { platforms, url, description } = props
const shareLinks: string[] = []
platforms.forEach((platform) => {
if (platform === 'pinterest') {
shareLinks.push(`https://pinterest.com/pin/create/button/?url=${props.url}&media=${props.image}&description=${props.description}`)
}
if (platform === 'facebook') {
shareLinks.push(`https://www.facebook.com/sharer/sharer.php?u=${props.url}`)
}
if (platform === 'twitter') {
shareLinks.push(`https://twitter.com/intent/tweet?text=${props.description}`)
}
})
return shareLinks
}
let shouldRequireImage = fn({
pageTitle: 'Cool page',
platforms: ['facebook', 'pinterest'],
url: 'http://www.example.org',
description: 'A really cool page',
image: 'AwesomeImage.jpg'
})
let shouldNotRequireImage = fn({
pageTitle: 'Cool page',
platforms: ['facebook', 'twitter'],
url: 'http://www.example.org',
description: 'A really cool page',
})
console.log(shouldRequireImage)
console.log(shouldNotRequireImage)
在使用带有“平台”索引的泛型时,hasPinterest 似乎总是给出 shareProps 的类型。我错过了什么?
【问题讨论】:
标签: typescript typescript-generics