【发布时间】:2021-05-29 21:57:36
【问题描述】:
我正在使用 typescript 和 next.js 开发一个项目,由于某些原因,未检查函数参数的类型。
我在下面提供了一个代码示例,我希望函数调用会抱怨我提供string 而不是SExpr。
abstract class SExpr {
abstract toString(): string
}
function parse(expr: SExpr) {
// ...
}
parse('123') // does not complain - compiles just fine
我以前从未遇到过这样的问题,并已尽力在tsconfig.json 中找到更改选项以解决此问题,但遗憾的是无法解决。
此时我怀疑 next.js 可能会覆盖我的 tsconfig.json 或类似的东西,因为我在使用 typescript 时从未遇到任何问题。
我的tsconfig.json如下:
{
"compilerOptions": {
"target": "es6",
"lib": ["dom", "dom.iterable", "esnext"],
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"baseUrl": ".",
"noImplicitAny": true,
"allowJs": true,
"skipLibCheck": true,
"alwaysStrict": true,
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
【问题讨论】:
-
嗨!请在重现问题的问题中添加某种独立的代码示例。没有repro,人们很难帮助你。
-
我添加了一个指向我的仓库的链接! :)
-
这是设计使然。 TypeScript 有一个结构类型系统,而不是名义上的类型系统。
SExpr只有一个成员,而该成员恰好是所有 JavaScript 对象(包括字符串)上的成员。换句话说,typescript 的行为符合预期,您应该考虑一种不同的方法,例如使用可区分的联合而不是类层次结构来表示表达式之类的东西。 -
@AluanHaddad 嗯,很有道理,谢谢!随意发布答案,我会接受它
-
@Tim 请参阅minimal reproducible example。简而言之,链接还不够好。该问题应该能够独立存在,而不依赖于您可以随时删除的我们这边的资源。
标签: javascript typescript duck-typing structural-typing