0

我想我错过了一些关于如何在 Typescript 中使用 && 检查真实值的基本知识。

为什么 props.function 在 test1 中仍然是未定义的,并且必须像我在 test2 中那样进行检查。

import React from "react";

interface PropsModel {
    label?: string
    function?: Function,
}

function test1(props: PropsModel) {
    return (
        <div>
            {props.label && <p>{props.label}</p>} // props.label is checked for undefined
            {props.function && <button onClick={() => props.function()}>Dummy button</button>} // props.function is not checked for undefined
        </div>
    )
}

function test2(props: PropsModel) {
    return (
        <div>
            {props.label && <p>{props.label}</p>} // props.label is checked for undefined
            {props.function && <button onClick={() => {if (props.function) props.function()}}>Dummy button</button>} // props.function is checked for undefined
        </div>
    )
}

编辑 1:添加到操场的链接

链接到Typescript 游乐场

4

2 回答 2

1

我绝不是 TS 问题的专家,因为我也想知道这一点。到目前为止,我的假设与“范围”的级别有关。Aka 该onClick功能与您的组件具有不同的范围。如果您 100% 确定该功能将存在于 OnClick 中,您可以执行以下任一操作。

import React from "react";

export type Function = () => void;

export type Input = {
    label?: string;
    function?: Function;
}

function test1(props: Input) {
    return (
        <div>
            {props.label && <p>{props.label}</p>} // props.label is checked for undefined
            {props.function && <button onClick={() => (props.function as Function)()}>Dummy button</button>} // props.function is not checked for undefined
        </div>
    )
}

或者干脆

import React from "react";

interface PropsModel {
    label?: string
    function?: Function,
}

function test1(props: PropsModel) {
    return (
        <div>
            {props.label && <p>{props.label}</p>} // props.label is checked for undefined
            {props.function && <button onClick={() => props.function!()}>Dummy button</button>} // props.function is not checked for undefined
        </div>
    )
}

A!已添加到{props.function && <button onClick={() => props.function!()}>Dummy button</button>}此处的行中。!简单地告诉 TS,你 100% 确定可选类型此时肯定存在。

于 2021-09-24T11:22:07.633 回答
0

您的function属性是可选的。因此要使用这样的属性,我们必须使用可选链接

你需要做的是

function test1(props: PropsModel) {
    return (
        <div>
            {props.label && <p>{props.label}</p>}
            {props.function && <button onClick={() => props.function?.()}>Dummy button</button>} // props.function is checked for undefined then it will be called
        </div>
    )
}

请注意,要使用可选链接,您的打字稿版本必须是typescript >= 3.7

于 2021-09-24T11:39:42.430 回答