为什么从打字稿文件导入会搞乱类型检查

问题描述 投票:0回答:1

我有一个打字稿文件,仅导出常量 openapi 对象模式:

export default {
  "title": "Draft",
  "description": "A new draft listing",
  "type": "object",
  "additionalProperties": false,
  "required": [
    "id"
  ],
  "properties": {
    "id": {
      "type": "string"
    }
  }
}

然后我尝试将其作为组件添加到通用开放 api 架构(在另一个文件中):

import Draft from './__generated_schemas__/draft.js'

import { OpenAPIV3 } from 'openapi-types'

export const schema: OpenAPIV3.Document = {
  openapi: '3.1',
  info: {
    title: 'Properties API',
    version: '1.0.0',
    description:
      'Nice service description'
  },
  components: {
    schemas: {
      Draft
    }
  },
  paths: {}
}

如果我执行上述操作,我会收到 TS 的抱怨:

 packages/api/src/schema.ts(22,7): error TS2322: Type '{ title: string; description: string; type: string; additionalProperties: boolean; required: string[]; properties: { id: { type: string; }; }; }' is not assignable to type 'ReferenceObject | SchemaObject'.
   Type '{ title: string; description: string; type: string; additionalProperties: boolean; required: string[]; properties: { id: { type: string; }; }; }' is not assignable to type 'NonArraySchemaObject'.
     Types of property 'type' are incompatible.
       Type 'string' is not assignable to type 'NonArraySchemaObjectType | undefined'.

但是!我应该将 TS 文件中的 json 直接复制粘贴到 open-api 架构中,一切正常:

export const schema: OpenAPIV3.Document = {
  openapi: '3.1',
  info: {
    title: 'Properties API',
    version: '1.0.0',
    description:
      'Nice service description'
  },
  components: {
    schemas: {
      Draft: {
        "title": "Draft",
        "description": "A new draft listing",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id"
        ],
        "properties": {
          "id": {
            "type": "string"
          }
        }
      }
    }
  }

知道 TS 类型检查哪里出了问题吗?我 100% 确定对象架构是正确的,整体 open-api 架构也是如此......

typescript import typechecking
1个回答
0
投票

我相信关键在最后一行:

Type 'string' is not assignable to type 'NonArraySchemaObjectType | undefined'.

我不知道

NonArraySchemaObjectType
到底是什么,你必须查看类型,但我愿意打赌它是 3 个常量字符串的联合类型。 类似于:“数字”| '字符串' | “布尔值”。

当您使用不包含任何类型的单独文件时,打字稿将对每种类型进行猜测。

例如,您通过:

export default {
  "title": "Draft",
  "description": "A new draft listing",
  "type": "object",
  ...
}

对于

title
它看到一个字符串,因此它选择字符串类型。 对于
description
,它看到一个字符串,因此它选择字符串类型。 对于
type
,它看到一个字符串,因此它选择字符串类型...但是您不仅仅想要一个普通字符串,您希望该字符串是特定类型:
NonArraySchemaObjectType
。但因为根本没有打字提示,所以打字看起来与
title
description
完全相同。

它在同一个文件中工作的原因是因为您在创建对象时指定:

OpenAPIV3.Document

© www.soinside.com 2019 - 2024. All rights reserved.