TypeScript中的setTimeout应该使用哪种返回类型?

时间:2018-06-26 10:31:49

标签: typescript

考虑以下代码:

const timer: number = setTimeout(() => '', 1000);

Typescript引发错误:Type 'Timer' is not assignable to type 'number'.快速查找告诉我setTimeout返回NodeJS.Timer

但是,如果我正在进行基于浏览器的开发,那么使用NodeJS.Timer会感到错误。哪种正确的类型定义或返回类型可以使setTimeout工作而无需借助any声明?

5 个答案:

答案 0 :(得分:13)

最简单的解决方案是允许类型推断起作用,而根本不指定任何类型。如果需要指定类型,请参见浏览器声明和节点声明之间的类型不一致,可以使用ReturnType来指定变量的类型为setTimeout的返回类型:

const timer: ReturnType<typeof setTimeout> = setTimeout(() => '', 1000);

或者,也可以使用window.setTimeout来代替setTimeout。返回正确的返回类型。

答案 1 :(得分:6)

发生这种情况是因为Typescript将在node_modules/@types下搜索类型定义

如果在~/node_modules/@types/node/globals.ts中安装NodeJS类型定义(带有许多npm软件包),而项目在~/Projects/myproject中,则这些定义将泄漏。

默认情况下,所有可见的“ @types”软件包都包含在您的 汇编。任何封闭文件夹的node_modules / @ types中的软件包 被认为是可见的;具体来说,这意味着 ./node_modules/@types/,../node_modules/@types/, ../../node_modules/@types/,依此类推。

请参阅:https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types

如果Typescript找到自定义类型定义,则其优先级高于默认类型定义。 VS Code 2 type definitions of setTimeout()

解决方案:

  • 指定compilerOption来搜索类型定义的路径:"typeRoots":[]
  • 指定editorOption的类型,以从默认路径中加载定义:"types": []
  • 从默认搜索路径中删除定义文件

答案 2 :(得分:3)

您可以使用window.setTimeout返回一个number类型。

let a: number;
a = window.setTimeout(function() {}, 0);

答案 3 :(得分:1)

对于其他有此错误的人,对我有用的是在tsconfig.js文件中添加:

"compilerOptions": {

   ...
   "types": [],
}

答案 4 :(得分:0)

import tkinter as tk import random import string handle = open('dictionary.txt') words = handle.readlines() handle.close() grid_size = 10 words = [ random.choice(words).upper().strip() \ for _ in range(5) ] print ("The words are:") print(words) grid = [ [ '_' for _ in range(grid_size) ] for _ in range(grid_size) ] orientations = [ 'leftright', 'updown', 'diagonalup', 'diagonaldown' ] class Label(tk.Label): def __init__(self, parent, **kwargs): super().__init__(parent, **kwargs, font=("Courier", 44)) #self.bind('<Button-1>', self.on_click) #def on_click(self, event): #w = event.widget #row, column = w.grid_info().get('row'), w.grid_info().get('column') #print('coord:{}'.format((row, column))) #w.destroy() class App(tk.Tk): def __init__(self): super().__init__() for row in range(grid_size): for column in range(grid_size): for word in words: word_length = len(word) placed = False while not placed: orientation = random.choice(orientations) if orientation == 'leftright': step_x = 1 step_y = 0 if orientation == 'updown': step_x = 0 step_y = 1 if orientation == 'diagonalup': step_x = 1 step_y = -1 if orientation == 'diagonaldown': step_x = 1 step_y = 1 x_position = random.randrange(grid_size) y_position = random.randrange(grid_size) ending_x = x_position + word_length*step_x ending_y = y_position + word_length*step_y if ending_x < 0 or ending_x >= grid_size: continue if ending_y < 0 or ending_y >= grid_size: continue failed = False for i in range(word_length): character = word[i] new_position_x = x_position + i*step_x new_position_y = y_position + i*step_y character_at_new_position = grid[new_position_x][new_position_y] if character_at_new_position != '_': if character_at_new_position == character: continue else: failed = True break if failed: continue else: for i in range(word_length): character = word[i] new_position_x = x_position + i*step_x new_position_y = y_position + i*step_y grid[new_position_x][new_position_y] = character if ( grid[row][column] == grid[new_position_x][new_position_y] ): grid[row][column] = grid[new_position_x][new_position_y] Label(self, text=character).grid(row=row, column=column) placed = True #if ( grid[row][column] == '_' ): #txt = random.SystemRandom().choice(string.ascii_uppercase) #Label(self, text=txt).grid(row=row, column=column) if __name__ == '__main__': App().mainloop() 返回If Target.Cells.CountLarge = 1 Then If Target.Column = 13 And Target.Value <> "" And Evaluate("COUNTIF(" & Target.Address & ",""*@*.*"")") <> 1 Then MsgBox "Email address ''" & Target.Value & "'' in " & Target.Address & " is not a valid email address." & _ vbNewLine & "Please enter a valid email address." Target.ClearContents Target.Activate End If End If 。理想情况下,您希望定义自己的类型以将其与数字区分开(并防止某些window.setTimeout操作对计时器没有意义)。

number
相关问题