Type 'string' is not assignable to type '“inherit” | “initial” | “unset” | “fixed” | “absolute” | “static” | “relative” | “sticky”'

前端 未结 4 1606
执笔经年
执笔经年 2020-12-25 10:16

I get the following error in my application (npm 5.4.2, react 15.4, typescript 2.5.3, webpack 2.2.1, webpack-dev-server 2.4.1).

This will work:



        
相关标签:
4条回答
  • 2020-12-25 10:31

    Use the React.CSSProperties type:

    import React, { CSSProperties } from "react";
    
    const myStyles: CSSProperties = {
      position: 'absolute',
    }
    

    Then just use the style as normal:

    <div style={myStyles} />
    
    0 讨论(0)
  • 2020-12-25 10:49

    This is a workaround, but it is alright. Some other solution is:

    const mystyles = {
       position: 'absolute',
    } as React.CSSProperties;
    

    You can check back when this issue will be solved. Around TS 2.6 i guess, judging by milestones.

    0 讨论(0)
  • 2020-12-25 10:52

    The answer by superluminary doesn't work if you have nested style objects. In this case you can create a type:

    import React, { CSSProperties } from 'react';
    
    export interface StylesDictionary{
        [Key: string]: CSSProperties;
    }
    

    And use it like so:

    const styles:StylesDictionary  = {
        someStyle:{
            display:'flex',
            justifyContent:'center',  
        },
        someOtherStyle:{
            display:'flex',
            justifyContent:'center',
            alignItems:'center',
            
        }
    }
    

    And then:

    <div style={styles.someStyle} />
    
    0 讨论(0)
  • 2020-12-25 10:55

    You can make TypeScript infer literal values on the entire object by using a const assertion:

    const mystyle = {
        position: 'absolute'            
    } as const;
    

    This way, if you add more properties to mystyle, it will work for them as well.

    0 讨论(0)
提交回复
热议问题