Search code examples
javascripttypescriptcore-motionemotion

How can I get fn({param}) of the param type in TypeScript?


I'm using raw emotion package npm i emotion and bumped to this question.

If I do this

import { css } from 'emotion';

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

If I hover the boxSizing, VSCode tells me that boxSizing type is

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

Now, I want to retrieve those type, resulting in this

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

Is there any utility method I can use to retrieve those types?

If I can just do

import { css } from 'emotion';

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

Is it possible to do this without installing any new npm package? I know emotion use csstype package for typings under the hood.


Solution

  • Since you don't want to install another package, here's what you can do:

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

    You may also find the Parameters generic type useful, although I don't believe it quite works here since Interpolation<T> is a union type of several items. Here's an example of how this can be used in another function:

    const example = (params: { boxSizing: 'border-box' }) => undefined
    
    type BoxSizing = Parameters<typeof example>[0]['boxSizing']