TypeScript中的可选参数可以为null吗?

时间:2019-07-28 17:42:36

标签: typescript undefined optional nullable

根据this article,当在TypeScript中启用严格的空检查时,除非为联合明确地允许,否则无法将nullundefined分配给变量。

// required value
let req: string;
req = "Something";  // OK
req = null;      // Error
req = undefined; // Error

// nullable value
let nbl: string | null;
nbl = "Something";  // OK
nbl = null;      // OK
nbl = undefined; // Error

但是TypeScript的可选值中是否允许null

// optional value
let opt?: string; // (actually invalid, as optional types cannot be used for variable declarations, but that's not the point, so imagine we are dealing with function parameters or something)
opt = "Something"; // OK
opt = null; // OK? Error?
opt = undefined; // OK

或者是

opt?: string;

等同于

opt: string | undefined;

是否像Microsoft's Coding guidelines所建议的那样不允许null

2 个答案:

答案 0 :(得分:2)

尝试后回答我自己的问题

类型nullundefined被作为单独的类型处理。 optional 类型是特殊的,还允许在函数调用中省略参数。

1。如果没有联合或可选,则除了类型本身之外,什么都不允许。

function foo(bar: string) {
    console.info(bar);
}

foo("Hello World!"); // OK
foo(null); // Error
foo(undefined); // Error
foo() // Error

2。要另外允许null,可以与null进行并集。

function foo(bar: string | null) {
    console.info(bar);
}

foo("Hello World!"); // OK
foo(null); // OK
foo(undefined); // Error
foo() // Error

3。允许undefined的工作方式与此类似。请注意,不能忽略该参数或null

function foo(bar: string | undefined) {
    console.info(bar);
}

foo("Hello World!"); // OK
foo(null); // Error
foo(undefined); // OK
foo() // Error

4。您也可以同时允许两者,但仍必须给出参数。

function foo(bar: string | null | undefined) {
    console.info(bar);
}

foo("Hello World!"); // OK
foo(null); // OK
foo(undefined); // OK
foo() // Error

5。使用 optional (可选),您可以省去参数,或传递undefined,但不能null

function foo(bar?: string) {
    console.info(bar);
}

foo("Hello World!"); // OK
foo(null); // Error
foo(undefined); // OK
foo() // OK

6。要允许所有这三种特殊情况,可以将 optional null组合在一起。

function foo(bar?: string | null) {
    console.info(bar);
}

foo("Hello World!"); // OK
foo(null); // OK
foo(undefined); // OK
foo() // OK

此外,可选仅可用于参数或其他类型声明(如接口),而不能用于常规变量。因为在分配变量时省略变量的值没有意义。

因此

let d?: string;

毫无意义,并导致编译错误。

答案 1 :(得分:0)

import sys from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget, QGraphicsView, QGraphicsScene, QGraphicsItem from PyQt5.QtCore import Qt, QRectF from PyQt5.QtGui import QBrush, QColor class GraphicsItem(QGraphicsItem): def __init__(self, parent): super().__init__() self.setFlag(QGraphicsItem.ItemIsFocusable) self.setFocus() self.screenSize = QDesktopWidget().screenGeometry(0) self.screenHeight = self.screenSize.height() self.screenWidth = self.screenSize.width() def boundingRect(self): self.posX = self.pos().x() # +++ self.posY = self.pos().y() # +++ return QRectF(0, 0, self.screenWidth, self.screenHeight) def paint(self, painter, option, widget): painter.setBrush(QBrush(Qt.magenta)) painter.drawRoundedRect(10, 10, 70, 70, 5, 5) # painter.drawEllipse(10, 100, 70, 70) def keyPressEvent(self, event): if event.key() == Qt.Key_Right: # self.moveBy(10, 0) if self.posX >= 1270: self.moveBy(-1270, 0) # +++ else: self.moveBy(10, 0) # +++ elif event.key() == Qt.Key_Left: # self.moveBy(-10, 0) if self.posX > 0: self.moveBy(-10, 0) # +++ else: self.moveBy(1270, 0) # +++ elif event.key() == Qt.Key_Down: # self.moveBy(0, 10) if self.posY >= 670: self.moveBy(0, -670) # +++ else: self.moveBy(0, 10) # +++ elif event.key() == Qt.Key_Up: # self.moveBy(0, -10) if self.posY > 0: self.moveBy(0, -10) # +++ else: self.moveBy(0, 670) # +++ # self.update() class GraphicsScene(QGraphicsScene): def __init__(self, parent): super().__init__(parent=parent) graphicsitem = GraphicsItem(self) self.addItem(graphicsitem) self.setBackgroundBrush(QColor(10, 155, 79)) self.screenSize = QDesktopWidget().screenGeometry(0) self.screenHeight = self.screenSize.height() self.screenWidth = self.screenSize.width() class GraphicsView(QGraphicsView): def __init__(self, parent): super().__init__(parent=parent) graphicsscene = GraphicsScene(self) self.screenSize = QDesktopWidget().screenGeometry(0) self.screenHeight = self.screenSize.height() self.screenWidth = self.screenSize.width() self.setGeometry(0, 0, self.screenWidth, self.screenHeight) self.setScene(graphicsscene) # self.show() class Widget(QWidget): def __init__(self): super().__init__() graphicsview = GraphicsView(self) self.screenSize = QDesktopWidget().screenGeometry(0) self.screenHeight = self.screenSize.height() self.screenWidth = self.screenSize.width() self.initUI() self.setFixedSize(self.screenWidth, self.screenHeight) # +++ def initUI(self): self.setWindowTitle("Graphics View") self.setGeometry(0, 0, self.screenWidth, self.screenHeight) # self.show() if __name__ == "__main__": app = QApplication(sys.argv) widget = Widget() widget.show() sys.exit(app.exec_()) 将该类型声明为let d?: string;

这是因为string | undefined是JS变量的默认值。