代码之家  ›  专栏  ›  技术社区  ›  Sventies

声明文件中的类型继承

  •  1
  • Sventies  · 技术社区  · 2 年前

    我声明了一个其他元素类型应该满足的“父”COMPONENT类型。如果我在普通的.ts或.tsx文件中使用它,下面的代码会很好地工作(也就是说,它会告诉我不能使用类型“hero”,因为它不是ELEMENT_type的一部分)。 然而,在声明文件中,这是不起作用的。

    如何声明泛型类型,然后将其用作“模具”,将其他更具体的类型放入声明文件中?

    declare type ELEMENT_TYPE = "div" | "p" | "h1" | "button";
    
    declare type COMPONENT = {
      type: ELEMENT_TYPE;
      children: (COMPONENT | string)[];
    };
    
    declare type Satisfies<T, U extends T> = U;
    
    declare type HERO = Satisfies<
      COMPONENT,
      {
        type: "hero";
        children: (COMPONENT | string)[];
      }
    >; // should throw error but does not in declaration (.d.ts) file
    
    

    我的tsconfig文件如下所示:

    {
      "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noEmit": true,
        "esModuleInterop": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve",
        "incremental": true,
        "plugins": [
          {
            "name": "next"
          }
        ],
        "paths": {
          "@/*": ["./*"]
        }
      },
      "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
      "exclude": ["node_modules"]
    }
    
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   jcalz    2 年前

    如果您希望TypeScript检查您的声明文件,则应禁用 the --skipLibCheck compiler option .

    推荐文章