当有string
&
number
类型时,我已经检查了一种类型,为什么打字稿抱怨另一种类型?
// tsconfig.json
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"jsx": "preserve",
"jsxImportSource": "solid-js",
"allowJs": true,
"noEmit": true,
"strict": true,
"noImplicitAny": true,
"types": ["vinxi/types/client", "bun-types"],
"isolatedModules": true,
"paths": {
"~/*": ["./src/*"]
}
}
如果t可以是
string | number
,那么可能有可能是
a: string
b: number
,反之亦然。打字稿要求您仅添加相同类型的值,因此您需要处理不同类型的合并。
type Add = {
// If both a and b are strings, return a string
(a: string, b: string): string;
// If both a and b are numbers, return a number
(a: number, b: number): number;
// If one is a string and the other is a number, return a string
(a: string | number, b: string | number): string;
};
const add: Add = (a, b) => {
// If both a and b are numbers, return the sum as a number
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
}
// If either a or b is a string, return the concatenation as a string
return (a.toString() + b.toString());
};
// Test cases
const result1 = add(1, 2); // 3 (number)
const result2 = add('a', 'b'); // "ab" (string)
const result3 = add('a', 1); // "a1" (string)
const result4 = add(1, 'b'); // "1b" (string)