【问题标题】:How can I specify a value must have a specific type without creating a variable for it?如何在不为其创建变量的情况下指定一个值必须具有特定类型?
【发布时间】:2018-11-30 21:45:10
【问题描述】:

说我有

type TypeMsAnimationDuration =
  | 75
  | 100
  | 150
  | 200
  | 250
  | 300
  | 350
  | 500;

const cssInJs = css`transition: all ${999}ms;`

如何确保值 '999' 是 TypeMsAnimationDuration 的值?

【问题讨论】:

    标签: typescript styled-components emotion


    【解决方案1】:

    如果不将其放入变量或创建必须调用以验证值的辅助函数,则无法执行此操作:

    type TypeMsAnimationDuration =
    | 75
    | 100
    | 150
    | 200
    | 250
    | 300
    | 350
    | 500;
    
    function animDuration(ms: TypeMsAnimationDuration) {
        return ms;
    }
    const cssInJs = css`transition: all ${animDuration(999)}ms;` // Error
    const cssInJs = css`transition: all ${animDuration(250)}ms;` // Ok
    

    【讨论】:

    • 是的,我做了完全相同的函数——我只是觉得让一个函数什么都不做但返回相同的值很奇怪,我认为 TypeScript 肯定有另一种方法来做到这一点。我相信使用 Flow 你可以这样做:const cssInJs = css`transition: all ${999: TypeMsAnimationDuration}ms;`
    • 有点类似,但您也可以尝试箭头函数:const cssInJs = (ms: TypeMsAnimationDuration) => { return css`transition: all ${ms}ms;` } 并像 cssInJs(999) // Error 一样使用它
    猜你喜欢
    • 2018-05-13
    • 2019-08-27
    • 2022-10-14
    • 2022-11-15
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    相关资源
    最近更新 更多