【问题标题】:How can I get fn({param}) of the param type in TypeScript?如何在 TypeScript 中获取参数类型的 fn({param})?
【发布时间】:2020-11-24 15:46:59
【问题描述】:

我正在使用原始emotionnpm i emotion 并碰到这个问题。

如果我这样做

import { css } from 'emotion';

const test = css({
  boxSizing: 'border-box'
})

如果我悬停boxSizing,VSCode 会告诉我boxSizing 类型是

"border-box" | "-moz-initial" | "inherit" | "initial" | "revert" | "unset" | "content-box" | BoxSizingProperty[] | undefined

现在,我想检索那些类型,结果是这样的

type result = "border-box" | "-moz-initial" | "inherit" | "initial" | "revert" | "unset" | "content-box" | BoxSizingProperty[] | undefined

我可以使用任何实用方法来检索这些类型吗?

如果我能做到的话

import { css } from 'emotion';

type result = someUtility<typeof css, 'boxSizing'>

是否可以在不安装任何新的 npm 包的情况下做到这一点?我知道情感使用 csstype 包在引擎盖下打字。

【问题讨论】:

  • 不确定我是否理解你的问题,但如果你想要它的 boxSizing 类型,你可以从 import { BoxSizingProperty } from "csstype" 中得到它;
  • 但是我必须安装完全正确的csstype版本的emotion,并且emotion使用旧的csstype版本作为依赖。

标签: javascript typescript core-motion emotion


【解决方案1】:

由于您不想安装其他软件包,您可以执行以下操作:

import { ObjectInterpolation } from 'emotion'

type BoxSizing = ObjectInterpolation<undefined>['boxSizing'] // type BoxSizing = "-moz-initial" | "inherit" | "initial" | "revert" | "unset" | "border-box" | "content-box" | BoxSizingProperty[] | undefined

您可能还会发现Parameters generic type 很有用,尽管我不认为它在这里很有效,因为Interpolation&lt;T&gt; 是多个项目的联合类型。这是如何在另一个函数中使用它的示例:

const example = (params: { boxSizing: 'border-box' }) => undefined

type BoxSizing = Parameters<typeof example>[0]['boxSizing']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 2019-05-15
    • 2020-01-19
    相关资源
    最近更新 更多