代码之家  ›  专栏  ›  技术社区  ›  Asool

为什么typescript没有显示错误?(反应)

  •  0
  • Asool  · 技术社区  · 6 年前

    我有一个容器,如下所示:

    lass BurgerBuilder extends React.Component {
    
    state = {
        ingredients: {
            salad: 1,
            bacon: 1,
            cheese: 2, 
            meat: 2
        }
    }
    render() {
        return(
            <>
                <Burger ingredients={this.state.ingredients}/>
                <div>Build Controls</div>
            </>
        );
    }
    }
    

    我的汉堡功能组件包括以下代码

    export interface IBurgerProps {
        ingredients: {
            salad?: number,
            bacon?: number,
            cheese?: number, 
            meat?: number
        }
    }
    
    const burger = (props: IBurgerProps) =>{
        const transformedIngredients = Object.keys(props.ingredients).map(igKey=> {
            return [...Array(props.ingredients[igKey])].map((_, i) => {
                <BurgerIngredient key={igKey + i} type={igKey}/>
            })
        });
    

    理论上,如果我在容器(BurgerBuilder)中的配料对象中添加“Chicken:1”,我会得到一个错误。也就是说,typescript应该抱怨说我们不能把色拉:数字,培根:数字,奶酪:数字,肉:数字,鸡肉:数字分配给类型色拉:数字未定义,培根:数字未定义,奶酪:数字未定义,肉:数字未定义

    为什么我在Burger Builder的配料对象中添加“Chicken:1”时没有得到这个错误?

    只是试着理解打字并做出更多的反应。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Karol Majewski    6 年前

    typescript使用所谓的 子结构式系统 也就是说,只要你的物品有你要求的所有东西,其余的就不重要了。

    有一个 ongoing discussion 围绕介绍这个话题 准确的类型 语言。今天,人们需要使用一些有问题的技巧来让它发挥作用。

    同时,我建议使用接口描述组件之间的契约。在这种情况下, Ingredients 接口“是”吗?这是两个组件所依赖的。

    让我们从组件中抽象出来。示例模型可能如下所示:

    type IngredientName =
      | 'salad'
      | 'bacon'
      | 'cheese'
      | 'meat';
    
    type Ingredients = Record<IngredientName, number>
    

    用途:

    interface Props {}
    
    interface State {
        ingredients: Ingredients;
    }
    
    export class BurgerBuilder extends React.Component<Props, State> {
        state: State = {
            ingredients: {
                salad: 1,
                bacon: 1,
                cheese: 2,
                meat: 2,
                chicken: 2, // Error! Chicken is not on the list.
            },
        };
    }
    

    您可以阅读关于类型关系的更多信息 in the specification .

    推荐文章