TypeScript,React-为什么对于某些prop类型定义,ts会回落到任何状态?

时间:2019-02-14 16:15:30

标签: reactjs typescript

我有以下道具打字:

export interface ITouchable {
  isDisabled?: boolean;
  margin?: Margin;
  height?: number;
  bgColor?: string;
}

Margin在哪里:

type Margin =
  | {
      top?: number;
      bottom?: number;
      left?: number;
      right?: number;
    }
  | [number | undefined, number | undefined]
  | number;

但是当我使用Touchable时,margin设置为any

<Touchable margin="foo" /> // <-- should cause an error but ITouchable.margin?: any

我不知道为什么会这样。在TypeScript游乐场中,我得到了预期的行为。所有其他道具定义都是正确的:

<Touchable bgColor={5} /> // <-- type number is not assignable to string

如果我导入该填充类型并将其声明为填充类型,那就很好了

import { Padding } from "@types";

const pad: Padding = "foo" // <-- error as expected

如果我在与Padding相同的文件中声明ITouchable,也可以正常工作。但是在我看来,我应该能够从全局类型定义中导入并使用它们而不会出现此问题。

我的基本文件结构是

src ->
  @types ->
    index.ts // <-- Margin is defined here

  components ->
    Touchable.tsx // <-- Touchable, as well as ITouchable is defined here

router.tsx // <-- I'm using Touchable here (in my project root)

还有我的tsconfig中的一些可能相关的属性:

{
  "compilerOptions": {
    "types": ["react-native"],
    "baseUrl": ".",
    "paths": {
      "@components": ["src/components"],
      "@store": ["./src/store"],
      "@store/*": ["./src/store/*"],
      "@utils/*": ["./src/utils/*"],
      "@types": ["./src/@types"]
    }
  },
  "include": ["./src/**/*"]
}

1 个答案:

答案 0 :(得分:0)

发生这种情况的原因是因为我的router.tsx在我的./src目录之外。

router移至src后,将出现正确的类型定义。我敢肯定,问题是由我的baseUrlpaths变量引起的,但我不确定到底有多精确。

如果有人可以解释我如何通过编辑tsconfig(而不是更改项目结构)来解决此问题,我会很乐意将您的答案标记为正确。