unknown
type means that the type of variable is not known. It is the type-safe counterpart of any. We can assign anything to an unknown variable, but the unknown isn’t assignable to any other types except to unknown and any. To use an unknown type, we need to first assert its type or narrow it to a more specific type.
Table of Contents
- Unknown Type
- Type Assertion
- Narrowing the unknown Type
- Unknown Vs Any
- Any Type
- Unknown Type
Unknown type is a top type in TypeScript. You can assign anything to an unknown type.
let unknownVar:unknown; unknownVar = true; //boolean unknownVar = 10; //number unknownVar = 10n; //BigInt >>=ES2020 unknownVar = «Hello World»; //String unknownVar = [«1»,«2»,«3»,«4»] //Array unknownVar = {firstName:», lastName:»}; // Object unknownVar = null; // null unknownVar = undefined; // undefined unknownVar = Symbol(«key»); // Symbol |
You can assign unknown to a variable of type unknown and any.
let value: unknown; let value1:unknown = value; // OK let value2:any = value; // OK |
But cannot assign unknown to any other types.
let value: unknown; let value1: boolean = value; // Error let value2: number = value; // Error let value3: string = value; // Error let value4: object = value; // Error let value5: any[] = value; // Error let value6: Function = value; // Error |
Type Assertion
You can use the Type Assertion on an unknown type to let the compiler know the correct type.
let value: unknown; let value1: boolean = value as boolean; // OK let value2: number = value as number; // OK let value3: string = value as string; // OK let value4: object = value as object; // OK let value5: any[] = value as any; // OK let value6: Function = value as Function; // OK |
Narrowing the unknown Type
Another way is to narrow the types using type guards.
let value: unknown; if (typeof value ==«boolean») { let value1: boolean = value; // OK } if (typeof value ==«number») { let value1: number = value; // OK } if (typeof value ==«string») { let value1: string = value; // OK } |
Unknown Vs Any
Both Any & Unknown data types are used when we do not know the Type.
Any Type
- You can assign anything to any type
- You can perform any operation on any type
For Example, the following code does not throw any compiler errors. But this will result in run time errors. This is one of the major issues with using any type. This is why you should avoid using Any.
let anyVar: any; anyVar.someMethod() anyVar[0] new anyVar(); |
Unknown Type
- You can assign anything to unknown type
- You cannot perfom any operation on unknown type unless you perform a type check or type assertion
The above code with unknown type results in compiler error (Object is of type 'unknown'.
).
let anyVar: unknown; anyVar.someMethod() //<span style=»background-color: inherit;»>Object is of type ‘unknown'</span> anyVar[0] new anyVar(); |
The following code with the Any type does compile, but with Unknown type throws compile error.
function addNum(num1: unknown, num2:unknown) { return num1+num2 ; //Object is of type ‘unknown’. } addNum(1,1) |
You need to use the Typeof type guard to narrow the type to number to make it work without any issue. With this approach, you are sure not to get any run time errors. This is why the unknown type is recommended over Any type.
function addNum(num1: unknown, num2:unknown) { if (typeof num1==«number» && typeof num2 == «number») { return num1+num2 ; } return 0 } addNum(1,1) |
Read More
- TypeScript Tutorial
- Typescript Type System
- Type Annotations in TypeScript
- Type Inference in typescript
- Number Data Type
- NaN in Typescript
- Min, Max & Safe Values
- EPSILON & Floating Point Precision
- Infinity
- BigInt data type
- BigInt Vs Number
- Boolean Data Type
- Null
- Undefined
- StrictNullChecks
- Null Vs Undefined
- Object & Object Data Type
- Never Type
- Void Type
- Unknown Type
From time to time, we come across situations where the type isn’t known beforehand, i.e. could be anything. Before TS v3, we would use the any
type for such types. But this comes with a few tradeoffs, like losing any type safety provided by Typescript.
Take the following example for instance:
const x: any = {
a: "a-value",
b: "b-value"
};
You can access the properties of the object above, i.e. x.a
and x.b
and everything would work as expected. The problem is that if you tried to access x.c
value, Typescript would not throw an error, since the object x
can be anything.
const c = x.c
console.log(c)
As you can see, this can be a source of many bugs, since common errors which Typescript would catch during build time will be allowed through. This is because when you use any
type, you opt out of type checking.
The unknown
type was introduced in version 3 of typescript as an accompanying type to any
. The unknown
type, when assigned to a variable, means that a variable type is not known.
And typescript doesn’t allow you to use a variable of unknown
type unless you either cast the variable to a known type or narrow its type. Type narrowing is the process of moving a less precise type to a more precise type. You can learn more about Type narrowing in Typescript here.
Take the following example.
const x: unknown = 1;
if we tried to square x
above without narrowing the type, typescript will throw the following error:
Object is of type 'unknown'.
To fix the above error, we can use type guards to check if it’s a number before squaring it.
if(typeof x === "number") {
console.log(x * x);
}
The same thing with the initial example, if we changed the type to unknown
and tried to access any of the properties, typescript would throw an error.
You would need to cast it, in order to typescript to allow you to use it.
const x: unknown = {
a: "a-value",
b: "b-value"
};
console.log((x as {a: string; b: string; }).b)
As you can see from the above examples, the unknown
type forces you to determine what a variable typed as unknown
is, either through type casting or type narrowing. This in turn leads to a better program, as typescript can then type checking the resulting type, leading to a more type-safe program.
Conclusion
In this article, we learned about the unknown
type and why we should use it to write more type-safe typescript programs. We also learned why you should avoid using type any
unless absolutely necessary.
If you found this article informative and would like to keep learning, visit my new series on Typescript — A Byte of Typescript. A Byte of Typescript is a new series that I will be publishing on a regular basis to help you demystify Typescript.
- Type Narrowing in TypeScript
- Types and Mocking — Typescript
- Template Literal Types in TypeScript
- Transforming Types in TypeScript with Utility Types
There are data types in TypeScript that are better known than others. Today I would like to introduce a less known data type: unknown
.
The unknown
data type
The unknown
type exists since TypeScript 3.0 (the current version is 4.2) and is a top type.
Similar to the any
type, a variable of type unknown
accepts values of any type.
The difference is that a value of type any
can be assigned to variables of all types and a value of type unknown
can only be assigned to variables of the type any
or unknown
.
/**
* New variable of type unknown
**/
let test: unknown;
/**
* Assigning a value to an unknown variable
**/
test = 'hello world'; // Works!
test = 5; // Works!
test = false; // Works!
test = () => false // Works!
test = new Audio(); // Works!
/**
* Using an unknown variable
**/
let myString: string = test; // Error: Type 'unknown' is not assignable to type 'string'
let myBool: boolean = test; // Error: Type 'unknown' is not assignable to type 'booelan'
const test2: unknown = test; // Works!
const test3: any = test; // Works!
test.foo(); // Error: Object is of type 'unknown'
new test(); // Error: Object is of type 'unknown'
Enter fullscreen mode
Exit fullscreen mode
When to use unknown
?
unknown
forces type checking and is safer than any
. That’s why its use should always be favored over any
.
Here is an example with JSON.parse()
, which always returns a value of type any
.
In the following situation the code will compile without noticing that there is a huge error. The JSON string is not of type IPerson
and should not be assignable to the variable phoebe
.
interface IPerson {name: string, age: number}
const jsonString = '{"alias": "rose", "color": "red"}';
const person = JSON.parse(jsonString); // This returns any
const phoebe: IPerson = person; // This should throw a type error, but doesn't...
Enter fullscreen mode
Exit fullscreen mode
To make our code safer and catch the type error, we can use unknown
in combination with a custom Type Guard.
interface IPerson {name: string, age: number}
const jsonString = '{"name": "rose", "age": 25}';
const person: unknown = JSON.parse(jsonString); // This returns any.
const notPerson: IPerson = person; // Error Type 'unknown' is not assignable to type 'IPerson'.
/**
* Create a custom Type Guard to make sure that
* the parsed data is of type Person.
*/
const isPerson = (data: any): data is IPerson => {
return typeof data.name == 'string' && typeof data.age == 'number'
}
/**
* Use Type Guard.
*/
if(isPerson(person)){
console.log('This is a person!');
// With the Type Guard the assignement of the
// variable as type Person works.
const phoebe: IPerson = person;
} else {
throw Error('Parsed string is not a Person.')
}
Enter fullscreen mode
Exit fullscreen mode
Follow me on dev.to and twitter!
Credits
- The unknown Type in TypeScript by Marius Schulz
- When to use TypeScript unknown vs any by Ben Ilegbodu
Common Errors
Below you find a list of common TypeScript errors along with the buggy code and its fixed version.
If you’re interested in more TypeScript troubleshooting and best practices, check out our free TypeScript tutorials on YouTube. 📺 You can also follow TypeScript TV on Twitter to stay up to date. 🐤
- 1. TS1002
- 2. TS1005
- 3. TS1006
- 4. TS1015
- 5. TS1016
- 6. TS1029
- 7. TS1036
- 8. TS1038
- 9. TS1046
- 10. TS1055
- 11. TS1056
- 12. TS1064
- 13. TS1066
- 14. TS1068
- 15. TS1070
- 16. TS1095
- 17. TS1103
- 18. TS1109
- 19. TS1117
- 20. TS1127
- 21. TS1128
- 22. TS1149
- 23. TS1155
- 24. TS1160
- 25. TS1183
- 26. TS1192
- 27. TS1196
- 28. TS1202
- 29. TS1208
- 30. TS1218
- 31. TS1219
- 32. TS1225
- 33. TS1228
- 34. TS1243
- 35. TS1244
- 36. TS1259
- 37. TS1308
- 38. TS1337
- 39. TS1357
- 40. TS1361
- 41. TS1363
- 42. TS1371
- 43. TS1375
- 44. TS1378
- 45. TS1385
- 46. TS1389
- 47. TS1431
- 48. TS1432
- 49. TS1434
- 50. TS1471
- 51. TS2300
- 52. TS2304
- 53. TS2305
- 54. TS2306
- 55. TS2307
- 56. TS2314
- 57. TS2315
- 58. TS2322
- 59. TS2335
- 60. TS2339
- 61. TS2344
- 62. TS2345
- 63. TS2348
- 64. TS2349
- 65. TS2351
- 66. TS2352
- 67. TS2355
- 68. TS2361
- 69. TS2362
- 70. TS2364
- 71. TS2365
- 72. TS2366
- 73. TS2367
- 74. TS2368
- 75. TS2369
- 76. TS2370
- 77. TS2371
- 78. TS2372
- 79. TS2377
- 80. TS2378
- 81. TS2390
- 82. TS2391
- 83. TS2394
- 84. TS2395
- 85. TS2403
- 86. TS2411
- 87. TS2420
- 88. TS2428
- 89. TS2430
- 90. TS2440
- 91. TS2445
- 92. TS2448
- 93. TS2451
- 94. TS2454
- 95. TS2456
- 96. TS2459
- 97. TS2475
- 98. TS2488
- 99. TS2497
- 100. TS2503
- 101. TS2507
- 102. TS2511
- 103. TS2515
- 104. TS2528
- 105. TS2531
- 106. TS2532
- 107. TS2533
- 108. TS2538
- 109. TS2550
- 110. TS2551
- 111. TS2552
- 112. TS2554
- 113. TS2556
- 114. TS2558
- 115. TS2559
- 116. TS2564
- 117. TS2567
- 118. TS2571
- 119. TS2580
- 120. TS2582
- 121. TS2583
- 122. TS2584
- 123. TS2588
- 124. TS2595
- 125. TS2611
- 126. TS2613
- 127. TS2616
- 128. TS2652
- 129. TS2654
- 130. TS2656
- 131. TS2661
- 132. TS2663
- 133. TS2664
- 134. TS2665
- 135. TS2668
- 136. TS2669
- 137. TS2677
- 138. TS2678
- 139. TS2680
- 140. TS2683
- 141. TS2684
- 142. TS2686
- 143. TS2687
- 144. TS2689
- 145. TS2691
- 146. TS2693
- 147. TS2694
- 148. TS2695
- 149. TS2706
- 150. TS2709
- 151. TS2715
- 152. TS2717
- 153. TS2720
- 154. TS2722
- 155. TS2724
- 156. TS2730
- 157. TS2732
- 158. TS2739
- 159. TS2740
- 160. TS2741
- 161. TS2742
- 162. TS2749
- 163. TS2769
- 164. TS2774
- 165. TS2779
- 166. TS2786
- 167. TS2792
- 168. TS2794
- 169. TS2813
- 170. TS2814
- 171. TS4020
- 172. TS4025
- 173. TS4060
- 174. TS4063
- 175. TS4075
- 176. TS4081
- 177. TS4104
- 178. TS4112
- 179. TS4113
- 180. TS4114
- 181. TS5023
- 182. TS5024
- 183. TS5025
- 184. TS5054
- 185. TS5055
- 186. TS5058
- 187. TS5069
- 188. TS5070
- 189. TS5083
- 190. TS6053
- 191. TS6059
- 192. TS6133
- 193. TS6138
- 194. TS6196
- 195. TS6198
- 196. TS6504
- 197. TS7006
- 198. TS7008
- 199. TS7009
- 200. TS7010
- 201. TS7016
- 202. TS7017
- 203. TS7022
- 204. TS7026
- 205. TS7027
- 206. TS7030
- 207. TS7031
- 208. TS7034
- 209. TS7041
- 210. TS7044
- 211. TS7053
- 212. TS8020
- 213. TS17000
- 214. TS17004
- 215. TS17009
- 216. TS18004
- 217. TS18016
- 218. TS80005
TS1002
error TS1002: Unterminated string literal.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to close the string literal with an ending '
:
1 |
|
If you want to support multiline text, then you would have to use string concatenation:
1 |
|
Another solution would be using a template literal:
1 |
|
TS1005
error TS1005: ‘=’ expected.
Broken Code ❌
1 |
|
Fixed Code ✔️
You need to assign your type declaration using the =
character:
1 |
|
Alternatively you can declare an interface:
1 |
|
error TS1005: ‘;’ expected.
Broken Code ❌
1 |
|
Fixed Code ✔️
Use an implicit return:
1 |
|
TS1006
error TS1006: A file cannot have a reference to itself.
Broken Code ❌
1 |
|
Fixed Code ✔️
You cannot reference a file to itself (causes recursive loop). To fix the problem you have to update the reference path to point to another declaration file:
1 |
|
TS1015
error TS1015: Parameter cannot have question mark and initializer.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS1016
error TS1016: A required parameter cannot follow an optional parameter.
Broken Code ❌
1 |
|
Fixed Code ✔️
The easiest way to fix the error is to make age
optional as well:
1 |
|
Alternatively, you can flip the order of middleName
and age
. Be aware that this breaks the contract (signature) of the function and is considered a “breaking change”:
1 |
|
You could also make middleName
non-optional:
1 |
|
Yet another solution would be to assign a default value to middleName
so it won’t be optional by default. This allows age
to be optional then:
1 |
|
TS1029
error TS1029: ‘public’ modifier must precede ‘abstract’ modifier.
Broken Code ❌
1 |
|
Fixed Code ✔️
They keywords public
, private
, and protected
define the access to a class member. Access modifiers have to be defined first in TypeScript.
Solution 1:
1 |
|
Solution 2:
The visibility is public
by default, so you don’t have to explicitly declare it:
1 |
|
Video Tutorial
TS1036
error TS1036: Statements are not allowed in ambient contexts.
Broken Code ❌
1 |
|
Fixed Code ✔️
With declare global
an ambient context is created. TypeScript does not allow statements in such ambient context declaration which is why we have to change the statement into a declaration:
1 |
|
If you don’t want client
to be a function, you have to use the
var` keyword:
1 |
|
TS1038
error TS1038: A ‘declare’ modifier cannot be used in an already ambient context.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS1046
error TS1046: Top-level declarations in .d.ts files must start with either a ‘declare’ or ‘export’ modifier.
Broken Code ❌
1 |
|
Fixed Code ✔️
If you want to export a constant from a definition file (d.ts
), then you have to use the export
modifier:
1 |
|
TS1055
error TS1055: Type ‘
AxiosPromise
‘ is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS1056
error TS1056: Accessors are only available when targeting ECMAScript 5 and higher.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
Set the “target” property in your “tsconfig.json” file to “es5” or higher:
1 |
|
TS1064
error TS1064: The return type of an async function or method must be the global Promise type. Did you mean to write ‘Promise ‘?
Broken Code ❌
1 |
|
Fixed Code ✔️
If your function is asynchronous, your return value must be wrapped with Promise<...>
:
1 |
|
TS1066
error TS1066: In ambient enum declarations member initializer must be constant expression.
Broken Code ❌
1 |
|
Fixed Code ✔️
Try to replace your enum declaration with a type:
1 |
|
TS1068
error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
Broken Code ❌
1 |
|
Fixed Code ✔️
Functions that are part of a class are being called “method”. The method of a class is defined without the function
keyword:
1 |
|
TS1070
error TS1070: ‘private’ modifier cannot appear on a type member.
Broken Code ❌
1 |
|
Fixed Code ✔️
Interfaces are structures that define the public contract. This prohibits you from using private
modifiers. Only public
and protected
can be used. To solve the problem, the private
keyword must be removed from the name
property of the Animal
interface:
1 |
|
Video Tutorial
TS1095
error TS1095: A ‘set’ accessor cannot have a return type annotation.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to remove the return type from the “set” accessor:
1 |
|
TS1103
error TS1103: ‘for await’ loops are only allowed within async functions and at the top levels of modules.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to mark your function with the async
keyword:
1 |
|
TS1109
error TS1109: Expression expected.
Broken Code ❌
1 |
|
Fixed Code ✔️
Any snippet of code that evaluates to a value is an expression. Any snippet of code that performs an action is a statement. We need a statement to throw an error inside:
1 |
|
TS1117
error TS1117: An object literal cannot have multiple properties with the same name in strict mode.
Broken Code ❌
1 |
|
Fixed Code ✔️
We can only have one value per property:
1 |
|
TS1127
error TS1127: Invalid character.
Broken Code ❌
1 |
|
Fixed Code ✔️
Unlike in Python, inline comments cannot begin with a single hash sign (#
) in TypeScript. You must use 2 slashes:
1 |
|
TS1128
error TS1128: Declaration or statement expected.
Broken Code ❌
1 |
|
Fixed Code ✔️
A declaration specifies the data and a statement specifies some action with that data:
1 |
|
TS1149
TS1149: File name differs from already included file name only in casing.
Broken Code ❌
This error occurs when you import the same file in two different files using two different casing styles (ex. camelCase and UpperCamelCase):
File A:
1 |
|
File B:
1 |
|
Fixed Code ✔️
The error can be fixed by using the same casing style:
File A:
1 |
|
File B:
1 |
|
Alternatively, you can set forceConsistentCasingInFileNames
to false
in your “tsconfig.json” file:
1 |
|
TS1155
error TS1155: ‘const’ declarations must be initialized.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
Alternatively you can define a block-scoped local variable:
1 |
|
TS1160
error TS1160: Unterminated template literal.
Broken Code ❌
1 |
|
Fixed Code ✔️
This error is similar to TS1002 but refers to the ending of a template literal. To fix it, we have to close the template literal with an ending `
:
1 |
|
TS1183
error TS1183: An implementation cannot be declared in ambient contexts.
Broken Code ❌
1 |
|
Fixed Code ✔️
You cannot write a function implementation inside a declaration file (*.d.ts
). You can only declare its signature:
1 |
|
Alternatively, you can write your function implementation inside a source code file (*.ts
).
TS1192
error TS1192: Module ‘
json5
‘ has no default export.
Broken Code ❌
1 |
|
Fixed Code ✔️
When you are importing a module with built-in TypeScript declarations and TypeScript tells you that this module does not have a default export, then you can solve this problem by adding “allowSyntheticDefaultImports” to your “tsconfig.json” file and setting it to true
:
1 |
|
error TS1192: Module ‘
.../logdown
‘ has no default export.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
error TS1192: ‘export *’ does not re-export a default.
Broken Code ❌
1 |
|
You have to re-export a default (in this case coming from runWhenReady.ts
):
Fixed Code ✔️
1 |
|
TS1196
error TS1196: Catch clause variable type annotation must be ‘any’ or ‘unknown’ if specified.
Broken Code ❌
1 |
|
Fixed Code ✔️
Errors in catch clauses can only be typed with any
or unknown
. If you need a more precise error typing, you can use a type guard as follows:
1 |
|
Video Tutorial
TS1202
error TS1202: Import assignment cannot be used when targeting ECMAScript modules. Consider using ‘import * as ns from “mod”‘, ‘import {a} from “mod”‘, ‘import d from “mod”‘, or another module format instead.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS1208
error TS1208: ‘index.ts’ cannot be compiled under ‘–isolatedModules’ because it is considered a global script file. Add an import, export, or an empty ‘export {}’ statement to make it a module.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
To solve the issue you can turn off “isolatedModules” in your “tsconfig.json”. If you want to keep going with isolated modules, then you have to add an import or export to your code:
1 |
|
TS1218
error TS1218: Export assignment is not supported when ‘–module’ flag is ‘system’.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS1219
error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the ‘experimentalDecorators’ option in your ‘tsconfig’ or ‘jsconfig’ to remove this warning.
Broken Code ❌
1 |
|
Fixed Code ✔️
Simply set “experimentalDecorators” to true
in your “tsconfig.json” file. As long as decorators are experimental you will also have to install the reflect-metadata package to shim the upcoming Metadata Reflection API for ECMAScript. For proper functionality the “emitDecoratorMetadata” option should also be set to true
.
TS1225
error TS1225: Cannot find parameter ‘
error
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
A type predicate needs a parameter to validate:
1 |
|
TS1228
error TS1228: A type predicate is only allowed in return type position for functions and methods.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to separate the argument list from the return type definition by a :
:
1 |
|
TS1243
error TS1243: ‘static’ modifier cannot be used with ‘abstract’ modifier.
Solution
Broken Code ❌
1 |
|
Your abstract class
cannot define an abstract static
function. You have to keep it static
:
Fixed Code ✔️
1 |
|
error TS1243: ‘async’ modifier cannot be used with ‘abstract’ modifier.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS1244
error TS1244: Abstract methods can only appear within an abstract class.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS1259
error TS1259: Module can only be default-imported using the ‘esModuleInterop’ flag
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
1 |
|
Note: You can enable the ‘esModuleInterop’ flag also via the CLI:
1 |
|
TS1308
error TS1308: ‘await’ expressions are only allowed within async functions and at the top levels of modules.ts.
Broken Code ❌
1 |
|
Fixed Code ✔️
You cannot use an await
expression in an useEffect
hook, but you can use legacy Promise calls:
1 |
|
Alternatively, you can use an IIFE (Immediately-invoked Function Expression) in your useEffect
hook:
1 |
|
TS1337
error TS1337: An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
Alternative:
1 |
|
error TS1337: An index signature parameter type cannot be a union type. Consider using a mapped object type instead.
Broken Code ❌
1 |
|
Fixed Code ✔️
Solution with mapped object type:
1 |
|
Alternative:
1 |
|
TS1357
error TS1357: An enum member name must be followed by a ‘
,
‘, ‘=
‘, or ‘}
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS1361
error TS1361: ‘
Range
‘ cannot be used as a value because it was imported using ‘import type’.
Broken Code ❌
1 |
|
Fixed Code ✔️
The type Range
is being used to declare the return type of static function Ranger.getFullRange
but later on it is also being used to create an instance using new Range
. When you want to use a type to construct instances (or do anything else beyond declaring types), then you have to use the import
statement instead of import type
:
1 |
|
TS1363
error TS1363: A type-only import can specify a default import or named bindings, but not both.
Broken Code ❌
1 |
|
Fixed Code ✔️
With type-only imports and exports you cannot use a default import together with a named import in one single line of code. The TypeScript team chose this limitation to avoid ambiguity. You will have to use separate import statements:
1 |
|
TS1371
error TS1371: This import is never used as a value and must use ‘import type’ because ‘importsNotUsedAsValues’ is set to ‘error’.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
Solution 1:
When “importsNotUsedAsValues” is set to “error” in your “tsconfig.json”, then you have to use the “import type” syntax when you just want to refer to a type instead of using it as a value:
1 |
|
Solution 2:
Use the class also as a value and not just a type:
1 |
|
Solution 3:
You can also set “importsNotUsedAsValues” to “preserve” which is not recommended.
TS1375
error TS1375: ‘await’ expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty ‘export {}’ to make this file a module.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS1378
error TS1378: Top-level ‘await’ expressions are only allowed when the ‘module’ option is set to ‘es2022’, ‘esnext’, ‘system’, or ‘nodenext’, and the ‘target’ option is set to ‘es2017’ or higher.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS1385
error TS1385: Function type notation must be parenthesized when used in a union type.
Broken Code ❌
1 |
|
Fixed Code ✔️
When using a union type, you have to put additional function types in parentheses:
1 |
|
TS1389
error TS1389: ‘this’ is not allowed as a variable declaration name.
Broken Code ❌
1 |
|
Fixed Code ✔️
The name this
cannot be used to declare a variable because it is already a reserved keyword to refer to the current object in a method or constructor.
That’s why you have to choose a different name:
1 |
|
TS1431
error TS1431: ‘for await’ loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty ‘export {}’ to make this file a module.
Broken Code ❌
1 |
|
Fixed Code ✔️
Just add the imports for the fs
module and readline
module in order to turn your code into a module itself:
1 |
|
TS1432
error TS1432: Top-level ‘for await’ loops are only allowed when the ‘module’ option is set to ‘es2022’, ‘esnext’, ‘system’, ‘node16’, or ‘nodenext’, and the ‘target’ option is set to ‘es2017’ or higher.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
The error is similar to TS1378 and needs an adjustment in the tsconfig.json
file:
1 |
|
TS1434
error TS1434: Unexpected keyword or identifier.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to remove the duplicate static
keyword:
1 |
|
TS1471
TS1471: Module ‘
@headlessui/react
‘ cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead.
Broken Code ❌
1 |
|
Fixed Code ✔️
Using a dynamic import:
1 |
|
TS2300
error TS2300: Duplicate identifier ‘name’.
Broken Code ❌
Objects don’t support multiple properties with the same name:
1 |
|
Fixed Code ✔️
To fix the error we have to remove the duplicated property:
1 |
|
TS2304
error TS2304: Cannot find name ‘world’.
Broken Code ❌
1 |
|
Fixed Code ✔️
It can happen that TypeScript does not know about your global objects because those may be injected from an unknown runtime environment or third-party JavaScript library. The easiest way to let TypeScript know about this is to declare the ambience (ambient context):
1 |
|
error TS2304: Cannot find name ‘Promise’
Broken Code ❌
1 |
|
Fixed Code ✔️
Install es6-promise
type definitions with the typings tool.
1 |
|
Adding the following line to the beginning of every file using definitions from es6-promise
.
1 |
|
error TS2304: Cannot find name ‘Promise’
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
error TS2304: Cannot find name ‘FC’.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS2305
error TS2305: Module ‘
./sum
‘ has no exported member ‘multiply
‘.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
The file “sum.ts” exports a function named “sum”, so we have to fix the named import in our “main.ts” file:
1 |
|
TS2306
error TS2306: File ‘
add.ts
‘ is not a module.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
The error TS2306 signals that the file (add.ts
) can be found (otherwise it would throw error TS2307) but does not provide the necessary exports. We can solve this with a named export:
1 |
|
Alternatively we can use a default export:
1 |
|
Using a default export requires that we also adjust our import statement in main.ts
(otherwise we would end up with error TS2614):
1 |
|
TS2307
error TS2307: Cannot find module ‘events’ or its corresponding type declarations.
Broken Code ❌
You are importing from a core Node.js module (e.g. event
) without having Node.js type definitions installed:
1 |
|
Fixed Code ✔️
Import Node.js type definitions first in order to use Node.js core modules:
1 |
|
More: Error TS2307: Cannot find module events
TS2314
error TS2314: Generic type ‘
Omit
‘ requires 2 type argument(s).
Broken Code ❌
1 |
|
Fixed Code ✔️
When using the Omit
utility type, you have to list property overwrites with a pipe (|
):
1 |
|
TS2314: Generic type ‘
ReadonlyArray
‘ requires 1 type argument(s).
Broken Code ❌
1 |
|
Fixed Code ✔️
When using a generic (in this case ReadonlyArray<T>
), then you have to pass a type argument to it:
1 |
|
TS2315
error TS2315: Type ‘
CustomRequest
‘ is not generic.
Broken Code ❌
1 |
|
Fixed Code ✔️
When supplying a type (recognizable by the use of the diamond operator <>
), then we have to make sure that our type actually supports generics to capture the type that we provide:
1 |
|
TS2322
error TS2322: Type ‘string’ is not assignable to type ‘number’.
Broken Code ❌
1 |
|
Fixed Code ✔️
The type of the returned value must match the return type specified in the function signature:
1 |
|
Video Tutorial
TS2335
error TS2335: ‘super’ can only be referenced in a derived class.
Broken Code ❌
1 |
|
Fixed Code ✔️
Your derived class has to “extend” the base class:
1 |
|
TS2339
error TS2339: Property ‘
width
‘ does not exist on type ‘Shape
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
You can create discriminated unions by sharing a single field (e.g. kind
) in your type definitions and using a union type in connection with a switch-case statement that helps the TypeScript compiler to distinguish the different types:
1 |
|
TS2339: Property ‘
pop
‘ does not exist on type ‘readonly [1, 2, 3]
‘.
Broken Code ❌
1 |
|
When using a const assertion on an array, then your array becomes readonly (immutable), so you cannot modify its elements using in-place operations such as pop
. You will have to make your array mutable:
1 |
|
TS2344
error TS2344: Type ‘
{ name: string; }
‘ does not satisfy the constraint ‘{ age: number; }
‘. Property ‘age
‘ is missing in type ‘{ name: string; }
‘ but required in type ‘{ age: number; }
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
When passing a type argument, the required properties of the type variable (T
) must be matched:
1 |
|
As an alternative, type argument inference can be used:
1 |
|
TS2345
error TS2345: Argument of type ‘
number
‘ is not assignable to parameter of type ‘TimerHandler
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
There is a mismatch in the expected arguments of a function. The setTimeout
function expects the first argument to be a callback function and not the returned value (in this case a number
) of a function call:
1 |
|
Video Tutorial
TS2348
error TS2348: Value of type ‘typeof BaseN’ is not callable. Did you mean to include ‘new’?
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS2349
error TS2349: Cannot invoke an expression whose type lacks a call signature. Type ‘Promise‘ has no compatible call signatures.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS2351
error TS2351: This expression is not constructable. Type ‘
EMA
‘ has no construct signatures.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
1 |
|
TS2352
error TS2352: Conversion of type ‘
{ name: string; age: number; }
‘ to type ‘Person
‘ may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to ‘unknown
‘ first.
Broken Code ❌
1 |
|
Fixed Code ✔️
Make sure all properties of your object match the properties of your declared type:
1 |
|
Alternative but not recommended: Convert your object to unknown
first:
1 |
|
TS2355
error TS2355: A function whose declared type is neither ‘void’ nor ‘any’ must return a value.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS2361
error TS2361: The right-hand side of an ‘in’ expression must not be a primitive.
Broken Code ❌
1 |
|
Fixed Code ✔️
You cannot use the in
keyword on primitive data types. That’s why we have to replace the primitive type unknown
with a non-primitive type like object
:
1 |
|
An alternative solution would be to use a type assertion on the right-hand side of the ‘in’ expression:
1 |
|
TS2362
error TS2362: The left-hand side of an arithmetic operation must be of type ‘any’, ‘number’, ‘bigint’ or an enum type.
Broken Code ❌
1 |
|
Fixed Code ✔️
When you want to merge two objects, you have a multitude of possibilities:
Spread Syntax
1 |
|
Object.assign
1 |
|
TS2364
error TS2364: The left-hand side of an assignment expression must be a variable or a property access.
Broken Code ❌
1 |
|
Fixed Code ✔️
Using a variable on the left-hand side assignment:
1 |
|
TS2365
error TS2365: Operator ‘+’ cannot be applied to types ‘number’ and ‘object’.
Broken Code ❌
1 |
|
Fixed Code ✔️
You can use the +
operator only with equivalent data types (strings + strings or numbers + numbers):
1 |
|
TS2366
error TS2366: Function lacks ending return statement and return type does not include ‘undefined’.
Broken Code ❌
1 |
|
Fixed Code ✔️
The switch-case statement isn’t handling all cases from every possible input. We can solve that by defining a default
case:
1 |
|
Another solution would be to implement the missing case for 3
:
1 |
|
Video Tutorial
TS2367
error TS2367: This condition will always return ‘false’ since the types ‘{ message: string; }[] | undefined’ and ‘number’ have no overlap.
Broken Code ❌
1 |
|
Fixed Code ✔️
An array cannot be 0
, so doing a check for equality with 0
makes no sense. What may be useful instead is checking the array length:
1 |
|
TS2368
error TS2368: Type parameter name cannot be ‘number’.
Broken Code ❌
1 |
|
Fixed Code ✔️
The easiest way to fix the error is to make age
optional as well:
1 |
|
TS2369
error TS2369: A parameter property is only allowed in a constructor implementation.
Broken Code ❌
1 |
|
Fixed Code ✔️
The constructor implementation is missing curly brackets which is why TypeScript does not recognize the constructor implementation and files error TS2369. To solve it you have to add the missing curly brackets:
1 |
|
TS2370
error TS2370: A rest parameter must be of an array type.
Broken Code ❌
1 |
|
Fixed Code ✔️
A rest parameter allows a function to accept an indefinite number of parameters. To signal that it can be multiple values, we have to use an array
type for our rest parameter:
1 |
|
TS2371
error TS2371: A parameter initializer is only allowed in a function or constructor implementation.
Broken Code ❌
1 |
|
Fixed Code ✔️
Remove parameter initializer from function overload:
1 |
|
TS2372
error TS2372: Parameter ‘
score
‘ cannot reference itself.
Broken Code ❌
1 |
|
Fixed Code ✔️
If you want to use a default value for a parameter, then you have to set it to a fixed value instead of referencing the parameter to itself:
1 |
|
TS2377
error TS2377: Constructors for derived classes must contain a ‘super’ call.
Broken Code ❌
1 |
|
Fixed Code ✔️
Every constructor
in a derived class has to call the super
method to invoke the constructor
of the base class. It has to be the very first call:
1 |
|
Video Tutorial
TS2378
error TS2378: A ‘get’ accessor must return a value.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS2390
error TS2390: Constructor implementation is missing.
Broken Code ❌
1 |
|
Fixed Code ✔️
A constructor implementation must be put in curly brackets:
1 |
|
TS2391
error TS2391: Function implementation is missing or not immediately following the declaration.
Broken Code ❌
1 |
|
Fixed Code ✔️
An abstract class is different from an interface. You have to use the abstract
modifier if you want to define a contract in an abstract class. If there is no abstract
modifier you will have to provide a implementation.
Solution 1:
To solve the problem, we can mark makeNoise
with the abstract
keyword. That will enforce derived classes to implement this method on their own:
1 |
|
Solution 2:
Another solution is to provide a base implementation for makeNoise
:
1 |
|
Video Tutorial
TS2394
error TS2394: This overload signature is not compatible with its implementation signature.
Broken Code ❌
The implementation does not match all signatures:
1 |
|
Fixed Code ✔️
To match the first function overload, we have to add code to our function body which can also return a number
:
1 |
|
Video Tutorial
TS2395
error TS2395: Individual declarations in merged declaration ‘
React
‘ must be all exported or all local.
Broken Code ❌
1 |
|
Fixed Code ✔️
Make sure to export your additional declaration:
1 |
|
TS2403
error TS2403: TS2403: Subsequent variable declarations must have the same type. Variable ‘
window
‘ must be of type ‘Window & typeof globalThis
‘, but here has type ‘any
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS2411
error TS2411: Property ‘age’ of type ‘number’ is not assignable to ‘string’ index type ‘string’.
Broken Code ❌
1 |
|
Fixed Code ✔️
We defined an interface where every key
has a value of type string
. This doesn’t work for age
which is why we have to extend the possible value types using a union type:
1 |
|
TS2420
error TS2420: Class ‘Dog’ incorrectly implements interface ‘Animal’. Property ‘name’ is private in type ‘Dog’ but not in type ‘Animal’.
Broken Code ❌
1 |
|
Fixed Code ✔️
The Animal
interface defines a public name
member. The name
property in our Dog
class must therefore also be public:
1 |
|
Video Tutorial
TS2428
error TS2428: All declarations of ‘
Strategy
‘ must have identical type parameters.
Broken Code ❌
1 |
|
Fixed Code ✔️
Solution: The generic abstract class Strategy
has a generic type parameter list in angle brackets (diamond notation). This generic type parameter list must also be added to the interface definition of Strategy
.
1 |
|
TS2430
error TS2430: Interface ‘
StockExchange
‘ incorrectly extends interface ‘Exchange
‘.
Broken Code ❌
1 |
|
Fixed Code ✔
The address
in Exchange
is a mandatory property but in StockExchange
it is declared as being optional which
creates an incompatibility in the type. To fix the error, the property address
has either to become optional or mandatory in both
declarations:
1 |
|
TS2440
error TS2440: Import declaration conflicts with local declaration of ‘
React
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
You cannot redeclare a module that you are importing, but you can outsource your additional typings to a declaration file in order to apply declaration merging:
1 |
|
TS2445
error TS2445: Property ‘makeNoise’ is protected and only accessible within class ‘Dog’ and its subclasses.
Broken Code ❌
1 |
|
Fixed Code ✔️
The visibility of the makeNoise
method is protected. We have to make it public if we want to call it directly from an instance of Dog
:
1 |
|
Video Tutorial
TS2448
error TS2448: Block-scoped variable ‘add’ used before its declaration.
Broken Code ❌
Function expressions cannot be hoisted (used before they are declared):
1 |
|
Fixed Code ✔️
Turn your function expression into a function declaration (which can be hoisted):
1 |
|
TS2451
error TS2451: Cannot redeclare block-scoped variable ‘
window
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
Depending on the configuration of “lib” in your “tsconfig.json” file, there might be global variables that are present (like window
when using the “dom” library provided by TypeScript). In this case you cannot redeclare the global variable and have to choose another name:
1 |
|
TS2454
error TS2454: Variable ‘myFavoriteNumber’ is used before being assigned.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
or
1 |
|
TS2456
error TS2456: Type alias ‘
MyValue
‘ circularly references itself.
Broken Code ❌
1 |
|
Fixed Code ✔️
When defining a recursive type, you have to use the object syntax:
1 |
|
TS2459
error TS2459: Module ‘
./myFunction
‘ declares ‘myFunction
‘ locally, but it is not exported.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
When you want to import your function in another file, you have to make sure that it is exported using the export
keyword:
1 |
|
1 |
|
TS2475
error TS2475: ‘const’ enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query.
Broken Code ❌
1 |
|
Fixed Code ✔️
Defining a const enum
prevents TypeScript from generating JavaScript code for this enum. With const enum
TypeScript will just assume that the JavaScript equivalent of this code is already present.
If you want that TypeScript creates JS code for your enum definition, then you have to remove the const
keyword:
1 |
|
TS2488
error TS2488: Type ‘
{ [month: number]: string; }
‘ must have a ‘[Symbol.iterator]()
‘ method that returns an iterator.
Solution
You have to add a property called [Symbol.iterator]
to your object. The value of this property has to return an iterator. Here you can learn how to create an iterator.
Alternative Solution
If you run into this problem because of a for-of loop, then you can mitigate the problem by using the forEach()
method of arrays:
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS2497
error TS2497: Module ‘
logdown
‘ resolves to a non-module entity and cannot be imported using this construct.
Broken Code ❌
Export: logdown.d.ts
1 |
|
Import: app.ts
1 |
|
Broken Code ❌ #2
Export
1 |
|
Import
1 |
|
Note: TypeScript compiler option “allowSyntheticDefaultImports” must be set to true
.
Import
1 |
|
TS2503
error TS2503: Cannot find namespace ‘
React
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to add an import statement when reusing a different namespace. Also make sure to install type declarations (i.e. @types/react
) if needed.
1 |
|
error TS2503: Cannot find name ‘process’. Do you need to install type definitions for node? Try
npm i --save-dev @types/node
.
Solution
Run yarn add --dev @types/node
in your npm project.
TS2507
error TS2507: Type ‘
typeof EventEmitter
‘ is not a constructor function type.
Error happened when importing the exported class in another project.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
Read more
TS2511
error TS2511: Cannot create an instance of an abstract class.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
Read more: Passing a class constructor as parameter to a function.
TS2515
error TS2515: Non-abstract class ‘Dog’ does not implement inherited abstract member ‘makeNoise’ from class ‘Animal’.
Broken Code ❌
1 |
|
Fixed Code ✔️
If we derive a class from an abstract class, then we have to provide an implementation for all its abstract
members:
1 |
|
Video Tutorial
TS2528
error TS2528: A module cannot have multiple default exports.
Broken Code ❌
1 |
|
Fixed Code ✔️
Make sure to only have one default export:
1 |
|
TS2531
error TS2531: Object is possibly ‘null’.
Broken Code ❌
1 |
|
Fixed Code ✔️
The error originates from the fact that address
can be null
. To fix the problem, we can check if address
is null
by using optional chaining:
1 |
|
TS2532
error TS2532: Object is possibly ‘undefined’.
Broken Code ❌
1 |
|
Fixed Code ✔️
TypeScript warns us that person
can be undefined
(because of the ?
). There are multiple ways to fix the problem. We can do an existence check using an if
-condition:
1 |
|
Alternatively, we can use optional chaining:
1 |
|
Optional chaining is less preferable in this case as it will log undefined
if the person
is undefined
. Using the if
-condition from the solution above, nothing will be logged to the console in case the person
is undefined
.
TS2533
error TS2533: Object is possibly ‘null’ or ‘undefined’.
Broken Code ❌
1 |
|
Fixed Code ✔️
The error originates from the fact that address
can be undefined
(because of the ?
) or null
. To fix the problem, we can check if address
is defined by using optional chaining:
1 |
|
TS2538
error TS2538: Type ‘Person’ cannot be used as an index type.
Broken Code ❌
1 |
|
Fixed Code ✔️
You cannot use an interface as an index type, but you can use all keys of the interface using the keyof
type operator:
1 |
|
TS2550
error TS2550: Property ‘
setPrototypeOf
‘ does not exist on type ‘ObjectConstructor
‘. Do you need to change your target library? Try changing the ‘lib’ compiler option to ‘es2015’ or later.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
ES5, also known as ECMAScript 2009, doesn’t include Object.setPrototypeOf
which is why you have to upgrade to ES6 (also known as ES2015):
1 |
|
TS2551
error TS2551: Property ‘
title
‘ does not exist on type ‘Video
‘. Did you mean ‘titles
‘?
Broken Code ❌
1 |
|
Fixed Code ✔️
There is a typo in our code which TypeScript’s compiler has caught for us. We have to rename the titles
property:
1 |
|
TS2552
error TS2552: Cannot find name ‘readonlyArray’. Did you mean ‘ReadonlyArray’?
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS2554
error TS2554: Expected 2 arguments, but got 1.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
Video Tutorial
TS2556
error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter.
Broken Code ❌
1 |
|
Fixed Code ✔️
When calling a function using the spread syntax (...
), we have to ensure that the called function uses a rest
parameter:
1 |
|
TS2558
error TS2558: Expected 2 type arguments, but got 1.
Broken Code ❌
1 |
|
Fixed Code ✔️
The combine
function defines 2 type variables (X
& Y
), so you have to pass it 2 type arguments:
1 |
|
TS2559
error TS2559: Type ‘
{ city: string; }
‘ has no properties in common with type ‘User
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
The problem occurs with weak types (in this case User
). All properties of a weak type are optional but when your input doesn’t match any of the properties, you will get to see error TS2559. To fix it you have to match at least one of the optional properties:
1 |
|
TS2564
error TS2564: Property ‘name’ has no initializer and is not definitely assigned in the constructor.
This error can occur with TypeScript 2.7 in “strict” mode. TypeScript 2.7 introduced a new flag called --strictPropertyInitialization
, which tells the compiler to check that each instance property of a class gets initialized in the constructor body, or by a property initializer. See Strict Class Initialization.
Broken Code ❌
1 |
|
Fixed Code ✔️
We have to initialize the name
member either at its definition or within the constructor
.
Solution 1:
1 |
|
Solution 2:
1 |
|
Solution 3:
1 |
|
Video Tutorial
TS2567
error TS2567: Enum declarations can only merge with namespace or other enum declarations.
lib.dom.d.ts(18299, 6)
: ‘ResponseType’ was also declared here.
Broken Code ❌
1 |
|
Fixed Code ✔️
In the broken code shown above, a type ResponseType
is already declared as part of the “dom” typings. Enums can be merged with other enums but since the other declaration of ResponseType
is a type
, we cannot merge the existing declaration with our custom one. That’s why we have to remove “dom” from the “lib” entries in our “tsconfig.json” file or use a different name for our enum
:
1 |
|
TS2571
error TS2571: Object is of type ‘unknown’.
Broken Code ❌
If you use third-party libraries then it can happen that TypeScript cannot infer all return types. In such a case a return type can be unknown
which makes it impossible to access its properties from TypeScript. In the following example such case is constructed by assigning unknown
to an exemplary constant:
1 |
|
Fixed Code ✔️
To solve the problem of accessing properties from an unknown object, we have to define the type of the object which we want to access:
1 |
|
Broken Code ❌
1 |
|
Fixed Code ✔️
If your variable is of type unknown
, then you can use a type guard to narrow the type of your variable. If you want to be sure that you have an object at hand, you can use the typeof
type guard:
1 |
|
Alternative
You may also get the error “Object is of type ‘unknown’” when catching errors. In this case you have to type the error in your catch clause.
TS2580
error TS2580: Cannot find name ‘require’. Do you need to install type definitions for node? Try
npm i --save-dev @types/node
.
Broken Code ❌
1 |
|
Fixed Code ✔️
Install typings for Node.js:
1 |
|
Update code to modern import syntax:
1 |
|
TS2582
error TS2582: Cannot find name ‘test’. Do you need to install type definitions for a test runner? Try
npm i --save-dev @types/jest
ornpm i --save-dev @types/mocha
.
Broken Code ❌
1 |
|
Fixed Code ✔️
The error above is very specific to your testing framework and when using Jest it can be easily solved by installing definition files for Jest (npm i --save-dev @types/jest
).
When you are using Playwright, then you would have to make sure that you properly import Playwright’s definition for test
:
1 |
|
TS2583
error TS2583: Cannot find name ‘BigInt’. Do you need to change your target library? Try changing the ‘lib’ compiler option to ‘es2020’ or later.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
Arbitrary-precision integers (BigInt) were introduced in 11th edition of the ECMAScript Language Specification (ES11 / ES2020), so you have to add this information to the “lib” property of your TypeScript configuration to make use of this API:
1 |
|
Alternatively, you can make all additional APIs from ES2020 available to your code:
1 |
|
TS2584
error TS2584: Cannot find name ‘console’. Do you need to change your target library? Try changing the ‘lib’ compiler option to include ‘dom’.
Broken Code ❌
TypeScript code:
1 |
|
TypeScript compiler configuration (tsconfig.json
):
1 |
|
Fixed Code ✔️
You have to add the following to your “tsconfig.json” file:
1 |
|
When you are working on an application which never runs in a browser but only in Node.js environments, then you could add @types/node
to your devDependencies
instead of adding "dom"
to your "lib"
section.
TS2588
error TS2588: Cannot assign to ‘name’ because it is a constant.
Broken Code ❌
1 |
|
Fixed Code ✔️
You cannot reassign values to constants which is why you have to declare a variable using the let
keyword:
1 |
|
TS2595
error TS2595: ‘
React
‘ can only be imported by using a default import.
Broken Code ❌
1 |
|
Fixed Code ✔️
A default import cannot be put in curly braces:
1 |
|
TS2611
error TS2611: ‘
name
‘ is defined as a property in class ‘Person
‘, but is overridden here in ‘MyPerson
‘ as an accessor.
Broken Code ❌
1 |
|
Getters and setters are property accessors, so you have to make sure that you don’t mix property definitions with property accessor definitions. Using the accessor
keyword, you can turn a property into a property accessor:
1 |
|
TS2613
error TS2613: Module ‘
add
‘ has no default export. Did you mean to use ‘import { add } from "add"
‘ instead?
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
To fix the bug we have to convert our named export into a default export:
1 |
|
TS2616
error TS2616: ‘React’ can only be imported by using ‘import React = require(“react”)’ or a default import.
Broken Code ❌
1 |
|
Fixed Code ✔️
Use default import for React:
1 |
|
TS2652
error TS2652: Merged declaration ‘
MyPerson
‘ cannot include a default export declaration. Consider adding a separate ‘export default MyPerson
‘ declaration instead.
Broken Code ❌
1 |
|
Fixed Code ✔️
You cannot use the same name to declare a constant and a function. If your intention is to export your constant, then do the following:
1 |
|
TS2654
error TS2654: Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition.
Broken Code ❌
1 |
|
Fix
- Remove
/// <reference path="..." />
in.d.ts
files
Video Tutorial
TS2656
error TS2656: Exported external package typings file ‘
../proteus.d.ts
‘ is not a module. Please contact the package author to update the package definition.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS2661
error TS2661: Cannot export ‘
getSdk
‘. Only local declarations can be exported from a module.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
If you want to re-export getSdk
in another file, you have to export it first from its origin and then import it in the file where you want to re-export it:
1 |
|
1 |
|
TS2663
error TS2663: Cannot find name ‘
firstName
‘. Did you mean the instance member ‘this.firstName
‘?
Broken Code ❌
1 |
|
Fixed Code ✔️
If you want to use a getter, you need to back it up with a private property:
1 |
|
Starting from TypeScript 4.9, you can also use an auto-accessor field:
1 |
|
TS2664
error TS2664: Invalid module name in augmentation, module ‘
gas-local
‘ cannot be found.
Broken Code ❌
1 |
|
Fixed Code ✔️
The problem occurs when you want to write a module augmentation for a package that isn’t found in your “node_modules” directory. Make sure to install the module:
1 |
|
TS2665
error TS2665: Invalid module name in augmentation. Module ‘
gas-local
‘ resolves to an untyped module at ‘../node_modules/gas-local/index.js
‘, which cannot be augmented.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to move the shorthand ambient module declaration from a “.ts” file into a “.d.ts” file:
1 |
|
1 |
|
TS2668
error TS2668: ‘export’ modifier cannot be applied to ambient modules and module augmentations since they are always visible.
Info
Ambient modules
To describe the shape of libraries not written in TypeScript, we need to declare the API that the library exposes. We call declarations that don’t define an implementation “ambient”. Typically, these are defined in .d.ts
files. If you’re familiar with C/C++, you can think of these as .h
files.
Source: https://www.typescriptlang.org/docs/handbook/modules.html
Module Augmentation
With module augmentation, users have the ability to extend existing modules such that consumers can specify if they want to import the whole module or just a subset.
Source: https://blogs.msdn.microsoft.com/typescript/2016/02/22/announcing-typescript-1-8-2/
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
Usage
1 |
|
TS2669
error TS2669: Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.
Broken Code ❌
1 |
|
You have to turn your code into a module by adding an import
or export
statement to your code. The easiest way to solve the problem is exporting an empty object:
Fixed Code ✔️
1 |
|
TS2677
error TS2677: A type predicate’s type must be assignable to its parameter’s type. Type ‘
number
‘ is not assignable to type ‘string
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
The input
is declared to be of type string
which is why the type predicate cannot turn it into a number
because these two declarations are mutually exclusive. That’s why we have to declare an input type of any
:
1 |
|
TS2678
error TS2678: Type ‘
StreamStatus
‘ is not comparable to type ‘number
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
The StreamResponse
declares a “status” property of type number
but the switch-case statement checks against StreamStatus
, so we have to adjust the typing for “status” of StreamResponse
:
1 |
|
TS2680
error TS2680: A ‘this’ parameter must be the first parameter.
Broken Code ❌
1 |
|
Fixed Code ✔️
TypeScript requires that a this
parameter always comes first in the list of parameters:
1 |
|
TS2683
error TS2683: ‘this’ implicitly has type ‘any’ because it does not have a type annotation.
Broken Code ❌
1 |
|
Fixed Code ✔️
This bug is also a consequence of TS2680. To fix the bug we have to define the context of our function. It can be done by defining this
as the first parameter in our argument list and giving it a type annotation:
1 |
|
TS2684
error TS2684: The ‘
this
‘ context of type ‘void
‘ is not assignable to method’s ‘this
‘ of type ‘Person
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
When calling a function that defines a this
parameter, then we have to set the this
context with apply
, bind
or call
.
Using apply
:
1 |
|
Using bind
:
1 |
|
Using call
:
1 |
|
TS2686
error TS2686: ‘ko’ refers to a UMD global, but the current file is a module. Consider adding an import instead.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS2686: ‘sinon’ refers to a UMD global, but the current file is a module. Consider adding an import instead.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS2686: ‘React’ refers to a UMD global, but the current file is a module. Consider adding an import instead.
Broken Code ❌
1 |
|
Fixed Code ✔️
Use default import for React:
1 |
|
TS2687
error TS2687: All declarations of ‘status’ must have identical modifiers.
lib.dom.d.ts(11620, 14)
: ‘status
‘ was also declared here.
Broken Code ❌
1 |
|
Fixed Code ✔️
In the error above, a Response
is declared which should be merged (using declaration merging) with the Response
interface of the “dom” library which is set in “lib” within the “tsconfig.json” file. When merging with an existing declaration, the property types of the first declaration must be matched because you can only add additional properties when using declaration merging. The same rules applies to modifiers. Because “status” has a readonly modifier in the existing Response
interface, we must declare the same in our own interface extension:
1 |
|
TS2689
error TS2689: Cannot extend an interface ‘Animal’. Did you mean ‘implements’?
Broken Code ❌
1 |
|
Fixed Code ✔️
The TypeScript compiler tells us already the solution: When implementing an interface, we have to use implements
. If we inherit from classes, we use extends
.
1 |
|
TS2691
error TS2691: An import path cannot end with a ‘.d.ts’ extension. Consider importing ‘./index’ instead.
Broken Code ❌
You cannot directly import code from declaration files:
1 |
|
Fixed Code ✔️
You have to import functions from the source code file (e.g. index.ts
):
1 |
|
TS2693
error TS2693: ‘
Candlestick
‘ only refers to a type, but is being used as a value here.
Broken Code ❌
main.ts
1 |
|
Candlestick.ts
1 |
|
Fixed Code ✔️
main.ts
1 |
|
Candlestick.ts
1 |
|
TS2694
error TS2694: Namespace ‘
React
‘ has no exported member ‘NonExistent
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
When trying to import a type that is missing in an external namespace, then you have to add the missing typings yourself:
1 |
|
TS2695
error TS2695: Left side of comma operator is unused and has no side effects.
Broken Code ❌
1 |
|
Fixed Code ✔️
You just cannot leave out a callback parameter if you don’t want to use it. Mark it with an underscore (_
) instead:
1 |
|
TS2706
error TS2706: Required type parameters may not follow optional type parameters.
Broken Code ❌
1 |
|
Fixed Code ✔️
The generic type Key
is defined with a default value of string
which makes this type parameter not optional. However, the Value
type parameter is optional and optional parameters are not allowed to follow required parameters.
To solve the situation, we have can switch the position of the two parameters which would impact how we use the code:
1 |
|
Alternatively, we can also set a default type for Value
:
1 |
|
TS2709
error TS2709: Cannot use namespace ‘
globalThis
‘ as a type.
Broken Code ❌
1 |
|
Fixed Code ✔️
You cannot use a namespace as a type, but you can get the type assigned with that namespace by using the typeof
operator:
1 |
|
TS2715
error TS2715: Abstract property ‘name’ in class ‘Animal’ cannot be accessed in the constructor.
Broken Code ❌
1 |
|
Fixed Code ✔️
The name
member of the abstract Animal
class is abstract
, so we have to define it ourselves in the derived class Dog
. Because name
has no access modifier, it is public
by default which means that our Dog
class has to implement it with a public
visibility:
1 |
|
TS2717
error TS2717: Subsequent property declarations must have the same type. Property ‘
verbose
‘ must be of type ‘boolean
‘, but here has type ‘string
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
When declaring a property (in this case verbose
) twice, then the second declaration must follow the typings of the first declaration:
1 |
|
Usually the error TS2717 shows up when you have multiple versions of typings (i.e. @types/react
) for the same interfaces in your codebase. If you run into these kind of problems, you can inspect your typing resolutions using yarn why
(i.e. yarn why @types/react
) or npm explain
(i.e. npm explain @types/react
) to find out where you have conflicting typings.
TS2720
error TS2720: Class ‘
Dog
‘ incorrectly implements class ‘Animal
‘. Did you mean to extend ‘Animal
‘ and inherit its members as a subclass? Property ‘makeNoise
‘ is protected but type ‘Dog
‘ is not a class derived from ‘Animal
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
The implements
keyword is reserved to implement interfaces. If you want to work with class inheritance, you have to use extends
:
1 |
|
Video Tutorial
TS2722
error TS2722: Cannot invoke an object which is possibly ‘
undefined
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
Method invocation only works if the method is defined. The onClick
method of the event
object in the example above is optional, which means it can be undefined
. That’s why we have to make an existence check before calling / invoking it:
1 |
|
As of TypeScript 3.7 you can also use the optional chaining (?.
) operator to call a method on an object if it exists:
1 |
|
A third possibility is to use reference validation:
1 |
|
TS2724
error TS2724: ‘
./index
‘ has no exported member named ‘HeaderOptions
‘. Did you mean ‘HeaderOption
‘?
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
TypeScript noticed a typing error in the name of the imported interface. The code will work if we correct the typo:
1 |
|
TS2730
error TS2730: An arrow function cannot have a ‘this’ parameter.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to turn the arrow function expression into to a function declaration:
1 |
|
TS2732
error TS2732: Cannot find module ‘../../package.json’. Consider using ‘–resolveJsonModule’ to import module with ‘.json’ extension.
Broken Code ❌
1 |
|
Fixed Code ✔️
To fix the issue and allow importing JSON files, you have to set “resolveJsonModule” to true
in your “tsconfig.json” file.
TS2739
error TS2739: Type ‘
{}
‘ is missing the following properties from type ‘Person
‘:age
,name
Broken Code ❌
1 |
|
Fixed Code ✔️
The object doesn’t have any properties, so it cannot be assigned to the type of Person
. We have to add the missing properties to fix this error:
1 |
|
Video Tutorial
TS2739: Type ‘string[]’ is missing the following properties from type ‘Promise ‘: then, catch, [Symbol.toStringTag]
Broken Code ❌
1 |
|
When your function specifies to return a Promise, you have to ensure that your return value is also wrapped in a Promise
:
1 |
|
Alternatively, you can make use of the async
keyword, which will automatically wrap your return value into a Promise
:
1 |
|
TS2740
error TS2740: Type ‘
TextLine
‘ is missing the following properties from type ‘Position
‘: line, character, isBefore, isBeforeOrEqual, and 6 more.
Broken Code ❌
1 |
|
Fixed Code ✔️
The parameter startLine
is requiring a value of type Position
but the default value returns a value of type TextLine
, so this has to be fixed to return the expected type:
1 |
|
TS2741
error TS2741: Property ‘name’ is missing in type ‘{}’ but required in type ‘Animal’.
Broken Code ❌
1 |
|
Fixed Code ✔️
Interfaces can be used with classes or plain objects. If we want our object (i.e. laika
) to fulfill the contract of Animal
, we have to assign all required properties to it:
1 |
|
Video Tutorial
TS2742
error TS2742: The inferred type of ‘
ProductDeleteDocument
‘ cannot be named without a reference to ‘graphql-tag/node_modules/graphql/language/ast
‘. This is likely not portable. A type annotation is necessary.
Broken Code ❌
1 |
|
Fixed Code ✔️
TypeScript asks for a type annotation to explicitly resolve the inferred type, so let’s add a type annotation:
1 |
|
In a monorepository the error TS2742 can show up when you are using a package that has not set a “main” property in its “package.json” file. Sometimes it also happens that there is a “types” property which does not point to the correct typings. Make sure both paths are present and relative:
1 |
|
You can run into this error when a code generator, such as graphql-code-generator
, misses to render an important statement (see here). This can happen when the generator relies on implicit typings (type inference) and it can be fixed by instructing your code generator to render the missing import statement. Depending on your code generator this could be done through a config file:
1 |
|
TS2749
error TS2749: ‘
paramNames
‘ refers to a value, but is being used as a type here. Did you mean ‘typeof paramNames
‘?
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS2769
error TS2769: No overload matches this call.
Broken Code ❌
1 |
|
Fixed Code ✔️
There are only two function overloads for sum
. The first overload expects a
and b
to be of type number
. The second overload expects a
and b
to be of type string
but there is no overload that specifies a
to be a string
while b
is a number
. We have to add a third overload to allow such function calls:
1 |
|
An even easier solution would be to remove all function overloads as the function body allows us to use number
or string
through the union type of number | string
:
1 |
|
TS2774
error TS2774: This condition will always return true since this function is always defined. Did you mean to call it instead?
Broken Code ❌
1 |
|
Fixed Code ✔️
Both interfaces (MyPerson
& MyDog
) declare a function named age
, so that if
-condition to check for its existence is unnecessary:
1 |
|
TS2779
error TS2779: The left-hand side of an assignment expression may not be an optional property access.
Broken Code ❌
1 |
|
Fixed Code ✔️
You cannot assign a value to a property which might be undefined
. As Map.get() may return undefined
, you have to add an existence check:
1 |
|
TS2786
error TS2786: ‘
Component
‘ cannot be used as a JSX component.
Broken Code ❌
1 |
|
Fixed Code ✔️
Usually the problem derives from a mismatch in @types/react
. When you have libraries that are dependent on a specific version of @types/react
(i.e. v17.0.47) and you have other libraries working with another major version of @types/react
(i.e. v18.0.14), then this can cause compatibility issues when using React.ReactNode
or JSX.Element
. You have to streamline your dependencies on @types/react
, so that these follow the same major version.
You can find all libraries depending on @types/react
in your project by executing npm explain @types/react
(when a package-lock.json
file is present) or yarn why @types/react
(when a yarn.lock
file is present).
TS2792
error TS2792: Cannot find module ‘
@playwright/test
‘. Did you mean to set the ‘moduleResolution
‘ option to ‘node
‘, or to add aliases to the ‘paths
‘ option?
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
To fix the problem you have to use "moduleResolution": "node"
in your TS config:
1 |
|
TS2794
error TS2794: Expected 1 arguments, but got 0. Did you forget to include ‘
void
‘ in your type argument to ‘Promise
‘?
Broken Code ❌
1 |
|
Fixed Code ✔️
When a Promise resolves with nothing, you need to define that as a type argument to the generic Promise
:
1 |
|
TS2813
error TS2813: Class declaration cannot implement overload list for ‘MyClass’.
Solution
Broken Code ❌
1 |
|
Function declarations get hoisted, so you cannot give your class
the name of your function. Renaming your class solves the issue:
Fixed Code ✔️
1 |
|
TS2814
error TS2814: Function with bodies can only merge with classes that are ambient.
Solution
Broken Code ❌
1 |
|
Your function
cannot be named after your class
, so you will have to rename your function:
Fixed Code ✔️
1 |
|
Alternatively you can declare an ambient class which gets implemented by your function:
1 |
|
TS4020
error TS4020: ‘extends’ clause of exported class ‘
StrategyPOJO
‘ has or is using private name ‘Model
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS4025
error TS4025: Exported variable ‘
App
‘ has or is using private name ‘FC
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
When using an external type (like FC
) you also have to make sure that it is imported:
1 |
|
TS4060
error TS4060: Return type of exported function has or is using private name ‘JSX’.
Broken Code ❌
1 |
|
Fixed Code ✔️
The global JSX namespace is declared in @types/react
. You have to install the @types/react
package to make use of it:
1 |
|
TS4063
error TS4063: Parameter ‘
config
‘ of constructor from exported class has or is using private name ‘DoubleMovingAverageConfig
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS4075
error TS4075: Parameter ‘event’ of method from exported interface has or is using private name ‘Strategy’.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS4081
error TS4081: Exported type alias ‘
MyReturnType
‘ has or is using private name ‘getSdk
‘.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
The getSdk
is identified to be private because it is not exported. If we export the getSdk
function, we won’t have any more problems:
1 |
|
1 |
|
TS4104
error TS4104: The type ‘
readonly [1, 2, 3]
‘ is ‘readonly’ and cannot be assigned to the mutable type ‘[1, 2, 3]
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
Using a const assertion makes your array immutable, so you have to use the readonly
modifier for its type:
1 |
|
Alternative:
1 |
|
Alternative #2:
1 |
|
TS4112
error TS4112: This member cannot have an ‘override’ modifier because its containing class does not extend another class.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS4113
error TS4113: This member cannot have an ‘
override
‘ modifier because it is not declared in the base class ‘MyBaseClass
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
You can only override functions in our derived class when those exist in our base class. We can solve the error by overwriting an existing function:
1 |
|
Depending on our use case, we can also remove the override
modifier:
1 |
|
TS4114
error TS4114: This member must have an ‘
override
‘ modifier because it overrides a member in the base class ‘MyBaseClass
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
The error pops up when “noImplicitOverride” is set to true
in your “tsconfig.json” file, and you don’t use the override
modifier when overwriting a function from your base class. You can fix this by setting “noImplicitOverride” to false
(not recommended) or using the override
modifier (preferred solution):
1 |
|
TS5023
error TS5023: Unknown compiler option ‘
-c
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
If you want to point the TypeScript compiler to a different configuration, you have to use the --project
flag (see all tsc CLI options):
1 |
|
TS5024
error TS5024: Compiler option ‘lib’ requires a value of type string.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to define a valid set of high level libraries (such as “es6”) that are available in your runtime:
1 |
|
TS5025
error TS5025: Unknown compiler option ‘–no-emit’. Did you mean ‘noEmit’?
Broken Code ❌
1 |
|
Fixed Code ✔️
Use camel case writing:
1 |
|
TS5054
error TS5054: A ‘tsconfig.json’ file is already defined at: ‘
C:/dev/bennycode/ts-node-starter/tsconfig.json
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
You cannot initialize a new TypeScript compiler configuration when there is one already present. You have to delete the existing file first.
TS5055
error TS5055: Cannot write file because it would overwrite input file. Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
Alternatively, you can also skip compiling code (if you just want to check the types of your code):
1 |
|
TS5058
error TS5058: The specified path does not exist: ‘test.json’.
Broken Code ❌
1 |
|
Fixed Code ✔️
You probably don’t have a TS config named test.json
. Try to load tsconfig.json
:
1 |
|
TS5069
error TS5069: Option ‘declarationMap’ cannot be specified without specifying option ‘declaration’ or option ‘composite’.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to activate the “declaration” property before you can activate “declarationMap”:
1 |
|
TS5070
error TS5070: Option ‘–resolveJsonModule’ cannot be specified without ‘node’ module resolution strategy.
Broken Code ❌
1 |
|
Fixed Code ✔️
Just define the “moduleResolution” property and set it to “node”:
1 |
|
TS5083
error TS5083: Cannot read file ‘
base.json
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
Your TS config is extending another config (called base.json
) which cannot be found. Make sure that this file (base.json
) exists or remove your extends
property.
TS6053
error TS6053: File ‘
/typings/index.d.ts
‘ not found.
Broken Code ❌
1 |
|
Fixed Code ✔️
Use relative paths when using Triple-Slash Directives:
1 |
|
Read more: 8 Steps to Migrating from JavaScript to TypeScript
TS6059
error TS6059: File ‘
/root/project/packages/server/package.json
‘ is not under ‘rootDir’ ‘/root/project/packages/server/src
‘. ‘rootDir’ is expected to contain all source files.
Broken Code ❌
1 |
|
Fixed Code ✔️
When using require
then we can access files outside the specified root folder for input files (“rootDir” in “tsconfig.json”):
1 |
|
An even better solution would be changing the “rootDir” in your “tsconfig.json”, so that it includes the “package.json” file that you are trying to important. This may require you to also set “allowJs” to true
in your “tsconfig.json”.
TS6133
error TS6133: ‘
volume
‘ is declared but its value is never read.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
1 |
|
error TS6133: ‘
b
‘ is declared but its value is never read.
1 |
|
1 |
|
Fixed Code ✔️
You can remove the unused variable from your code or disable the check for unused variables in your TypeScript compiler config:
1 |
|
Video Tutorial
TS6138
error TS6138: Property ‘
lastName
‘ is declared but its value is never read.
Broken Code ❌
1 |
|
Fixed Code ✔️
Simply make use of the lastName
property:
1 |
|
TS6196
error TS6196: ‘
MyAbstractClass
‘ is declared but never used.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have three possibilities to fix the broken code:
- Make use of
MyAbstractClass
in your application - Export
MyAbstractClass
- Set “noUnusedLocals” to
false
in your “tsconfig.json”
1 |
|
TS6198
error TS6198: All destructured elements are unused.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to make use of the destructured values in your application / code:
1 |
|
TS6504
error TS6504: File ‘
mycode.js
‘ is a JavaScript file. Did you mean to enable the ‘allowJs
‘ option?
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to enable the “allowJS” flag in your “tsconfig.json” file:
1 |
|
Alternatively, you can enable it through the TypeScript Compiler CLI:
1 |
|
TS7006
error TS7006: Parameter ‘
person
‘ implicitly has an ‘any
‘ type.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
You have to define the type for the argument named person
:
1 |
|
Alternative, but not recommend:
- Set “noImplicitAny” to
false
in your “tsconfig.json”
TS7008
error TS7008: Member ‘
name
‘ implicitly has an ‘any’ type.
Broken Code ❌
1 |
|
Fixed Code ✔️
To fix the problem, you can initialize the class member so that TypeScript can infer the type:
1 |
|
Alternatively, you can annotate the type:
1 |
|
TS7009
error TS7009: ‘new’ expression, whose target lacks a construct signature, implicitly has an ‘any’ type.
Broken Code ❌
1 |
|
Fixed Code ✔️
The resolve
function of a Promise
is not a constructor. You can use the new
keyword only with constructors, so the new
keyword has to be removed in order to fix the code:
1 |
|
Alternatively, you can make use of the constructor:
1 |
|
TS7010
error TS7010: ‘
sum
‘, which lacks return-type annotation, implicitly has an ‘any
‘ return type.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to add a return-type annotation and preferably a function implementation:
1 |
|
TS7016
error TS7016: Could not find a declaration file for module ‘
uuidjs
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
Solution 1
The problem shows that uuidjs
is a plain JavaScript module and doesn’t ship with TypeScript declaration files (.d.ts
). That’s why we have to use the CommonJS import syntax to import this module in a Node.js environment:
1 |
|
Solution 2
A proper fix would be to have a uuidjs.d.ts
as part of uuidjs
: https://github.com/LiosK/UUID.js/issues/6
Example:
1 |
|
1 |
|
Solution 3
If external typings are available in the DefinitelyTyped repository, then you can also install external declarations from there:
1 |
|
Solution 4
If there are no declarations available and you want to use the module (in this case uuidjs
) with standard import syntax (not CommonJS), then you can create a shorthand ambient module declaration by creating a “*.d.ts” file and writing the following into it:
1 |
|
TS7017
error TS7017: Element implicitly has an ‘
any
‘ type because type ‘{}
‘ has no index signature.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to define the type for indexing your object properties (object["index"]
):
1 |
|
The name of the index can be freely chosen:
1 |
|
How to fix such errors in interfaces:
1 |
|
Alternative, but not recommend:
- Set “noImplicitAny” to
false
in your “tsconfig.json”
error TS7017: Element implicitly has an ‘
any
‘ type because type ‘typeof globalThis
‘ has no index signature.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
Reference:
- https://github.com/microsoft/TypeScript/issues/30139#issuecomment-913018222
TS7022
error TS7022: ‘
window
‘ implicitly has type ‘any
‘ because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
Broken Code ❌
1 |
|
1 |
|
Fixed Code ✔️
The above error can occur when TypeScript doesn’t know about the window interface. Make sure to add “dom” to your list of known runtime libraries in your compiler options:
1 |
|
TS7026
error TS7026: JSX element implicitly has type ‘any’ because no interface ‘JSX.IntrinsicElements’ exists.
Broken Code ❌
1 |
|
Fixed Code ✔️
The global JSX namespace is declared in @types/react
. You have to install the @types/react
package to make use of it:
1 |
|
TS7027
error TS7027: Unreachable code detected.
Broken Code ❌
1 |
|
Fixed Code ✔️
Your code cannot print text to the standard output when your program is told to exit beforehand, so you have to remove the call to exit or place it at a later point in time:
1 |
|
TS7030
error TS7030: Not all code paths return a value.
Broken Code ❌
1 |
|
Fixed Code ✔️
TypeScript reminds us that we forgot to return a value in case our if-condition doesn’t match. We can solve this problem in many ways.
Always return a value:
1 |
|
Add general else
:
1 |
|
Handle all cases
:
1 |
|
Add default
case:
1 |
|
Define that the return type can be void
:
1 |
|
Video Tutorial
TS7031
error TS7031: Binding element ‘age’ implicitly has an ‘any’ type.
Broken Code ❌
1 |
|
Fixed Code ✔️
TypeScript complains because it doesn’t know the type of the argument that we are destructuring. That’s why it sets all
its properties to the type of any
. To prevent that we have to define a type for the parameter of the printAge
function:
1 |
|
TS7034
error TS7034: Variable ‘
expectations
‘ implicitly has type ‘any[]
‘ in some locations where its type cannot be determined.
Broken Code ❌
1 |
|
Fixed Code ✔️
An array can collect values of different types, so we have to tell TypeScript which types we want to collect:
1 |
|
If we want to specify multiple types, we have to define a union type:
1 |
|
Alternative:
1 |
|
Unrecommended solutions:
- Set “noImplicitAny” to
false
in your “tsconfig.json”
TS7041
error TS7041: The containing arrow function captures the global value of ‘
this
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
Using this
is not allowed in arrow functions (source) because arrow functions aren’t made to work with call
, apply
and/or bind
methods (source). We have to replace our arrow function with an anonymous function declaration to prevent that our this
context gets captured:
1 |
|
Since ECMAScript 2015 (ES6) this can be shortened (Object Literal Property Value Shorthand) to:
1 |
|
TS7044
error TS7044: Parameter ‘
a
‘ implicitly has an ‘any
‘ type, but a better type may be inferred from usage.
Broken Code ❌
1 |
|
Fixed Code ✔️
From the body of the arrow function expression, TypeScript can see by the *
that a
and b
may be of type number
:
1 |
|
TS7053
error TS7053: Element implicitly has an ‘
any
‘ type because expression of type ‘string
‘ can’t be used to index type ‘Person
‘. No index signature with a parameter of type ‘string
‘ was found on type ‘Person
‘.
Broken Code ❌
1 |
|
Fixed Code ✔️
There are multiple ways to solve the error. You can define an index signature for the Person
interface which will allow all strings:
1 |
|
However, this is not recommend as it will allow you to access keys that are not defined (like age
):
1 |
|
The better solution is using the keyof
type operator which creates a literal union of its keys:
1 |
|
TS8020
error TS8020: JSDoc types can only be used inside documentation comments.
Broken Code ❌
1 |
|
Fixed Code ✔️
If you wanted to make c
optional:
1 |
|
If you wanted to document c
with JSDoc:
1 |
|
TS17000
error TS17000: JSX attributes must only be assigned a non-empty ‘expression’.
Broken Code ❌
1 |
|
Fixed Code ✔️
You can’t use an empty expression ({}
) in JSX attributes:
1 |
|
TS17004
error TS17004: Cannot use JSX unless the ‘–jsx’ flag is provided.
Broken Code ❌
1 |
|
Fixed Code ✔️
You have to add a configuration for “jsx” to your “tsconfig.json” file:
1 |
|
TS17009
error TS17009: ‘super’ must be called before accessing ‘this’ in the constructor of a derived class.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|
TS18004
error TS18004: No value exists in scope for the shorthand property ‘
age
‘. Either declare one or provide an initializer.
Broken Code ❌
1 |
|
Fixed Code ✔️
If you want to use the shorthand property name syntax to access the age
property, you have to make sure that this variable is defined in the first place:
1 |
|
Alternatively, you can avoid using the shorthand property name syntax:
1 |
|
TS18016
error TS18016: Private identifiers are not allowed outside class bodies.
Broken Code ❌
1 |
|
Fixed Code ✔️
Private properties can only be used in classes but not in interfaces. We therefore need to convert the interface into a class in order to be able to compile the code:
1 |
|
TS80005
error TS80005: ‘require’ call may be converted to an import.
Broken Code ❌
1 |
|
Fixed Code ✔️
1 |
|