React Native 如何使apply函数像使用typescript的顺风一样

yv5phkfx  于 2023-04-22  发布在  React
关注(0)|答案(1)|浏览(131)

如果我有这样代码

const AlignContent = {
    'content-start': {alignContent: 'flex-start'},
    'content-center': {alignContent: 'center'},
    'content-end': {alignContent: 'flex-end'},
    'content-stretch': {alignContent: 'stretch'},
    'content-between': {alignContent: 'space-between'},
    'content-around': {alignContent: 'space-around'},
}

const AlignItems = {
        'items-stretch': {alignItems: 'stretch'},
    'items-start': {alignItems: 'flex-start'},
    'items-center': {alignItems: 'center'},
    'items-end': {alignItems: 'flex-end'},
    'items-baseline': {alignItems: 'baseline'},
}

const styles = {
    ...AlignContent,
    ...AlignItems
}

function apply(styles: ??? ) {
  //apply code here
}

如何创建要引用keyof typeof styles接口,所以我想像这样调用apply:

apply('items-stretch content-around')

注意:???不是string类型,但我希望从keyof typeof styles中建议每个

k97glaaz

k97glaaz1#

您可以使用Template Literal Types来实现此目的。
在你的例子中,你可以这样写:

const AlignContent = {
    'content-start': {alignContent: 'flex-start'},
    'content-center': {alignContent: 'center'},
    'content-end': {alignContent: 'flex-end'},
    'content-stretch': {alignContent: 'stretch'},
    'content-between': {alignContent: 'space-between'},
    'content-around': {alignContent: 'space-around'},
}

type AlignContentKeys = keyof typeof AlignContent

const AlignItems = {
    'items-stretch': {alignItems: 'stretch'},
    'items-start': {alignItems: 'flex-start'},
    'items-center': {alignItems: 'center'},
    'items-end': {alignItems: 'flex-end'},
    'items-baseline': {alignItems: 'baseline'},
}

type AlignItemsKeys = keyof typeof AlignItems

const styles = {
    ...AlignContent,
    ...AlignItems
}

type Style = AlignContentKeys | AlignItemsKeys | `${AlignContentKeys} ${AlignItemsKeys}` | `${AlignItemsKeys} ${AlignContentKeys}`

function apply(styles: Style ) {
  //apply code here
}

你可以在我做的TSPlayground里看看。

相关问题