typescript - 如何在 TypeScript 中转换对象属性?

标签 typescript

我有一个简单的问题,我将 TypeScriptReact 一起使用,到目前为止效果很好,但我遇到了这个小问题。我是 TypeScript 的新手,但到目前为止我很喜欢它,真的让我想起了 Go

我正在尝试创建一种样式并将其作为对象传递到样式中,例如

import * as React from 'react'
import * as ReactDOM from 'react-dom'

export interface NavbarProps {
  title: string;
}

export class Navbar extends React.Component<NavbarProps, undefined> {
  render() {
    return (
      <div style={styles.navbar}>
        <div style={styles.navbarTitle}>
          <h1 style={styles.navbarTitle}>{ this.props.title }</h1>
        </div>
      </div>
    )
  }
}

// Lets it compile properly
let spaceBetween: "space-between" = "space-between";

let styles = {
  navbar: {
    display: 'flex',
    flexDirection: 'row',
    paddingLeft: '10px',
    paddingRight: '10px',
    height: '50px',
    color: 'white',
    backgroundColor: "#333",
    alignItems: "center",
    justifyContent: spaceBetween
  },
  navbarTitle: {
    margin: 0,
    padding: 0,
    letterSpacing: "1px"
  }
};

如果我删除 let spaceBetween: "space-between"= "space-between" 并尝试只执行 { justifyContent: "space-between"} 我得到一个错误,因为根据 CSSProperties Interface 的类型,它声明 justifyContent 是这样的:

/**
         * Defines how the browser distributes space between and around flex items
         * along the main-axis of their container.
         */
        justifyContent?: "flex-start" | "flex-end" | "center" | "space-between" | "space-around";

那么我怎样才能内联 justifyContent 而不是只为转换创建一个变量。

谢谢。

实际错误

src\public\views\components\navbar\navbar.tsx(11,12): error TS2322: Type '{ display: string; flexDirection: string; paddi
  Types of property 'justifyContent' are incompatible.
    Type 'string' is not assignable to type '"center" | "flex-start" | "flex-end" | "space-between" | "space-around"'.

最佳答案

您必须为 styles.navbar 指定正确的类型,例如

let styles = {
  navbar: {
    display: 'flex',
    flexDirection: 'row',
    paddingLeft: '10px',
    paddingRight: '10px',
    height: '50px',
    color: 'white',
    backgroundColor: "#333",
    alignItems: "center",
    justifyContent: "space-between"
  } as ViewStyle,  //<= here
...
}

关于typescript - 如何在 TypeScript 中转换对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41163837/

相关文章:

css - Bootstrap Dropdowns 按钮不适用于 Angular 8 组件

javascript - TypeScript 没有 window.eval()

javascript - Angular Admin Guard问题无法测试类型 'void'的表达式的真实性

javascript - 理解 TypeScript/Angular JS 中的定义顺序

javascript - webpack 中缺少 TypeScript 源文件映射 ://

typescript - 通用和映射类型缩小

javascript - 从具有父子结构的对象数组中删除对象

node.js - Mongoose 数组对象中的数字递增

TypeScript - 如何在编译时检查对象是否实现接口(interface)?

typescript - 模块导入返回空对象