简体   繁体   English

为什么打字稿会在散布组件中中断?

[英]Why does typescript break in components with spread?

Why does typescript break if you send props to a component with a spread statement?如果您将道具发送到带有扩展语句的组件,为什么打字稿会中断?

Example code示例代码

type SomeComponentProps = Readonly<{
  someTitle: string
}>

const SomeComponent = ({ someTitle }: SomeComponentProps) => {
  return <>someTitle</>
}

const MainComponent = () => {
  const someTitle = 'Some title'
  const TICK = 'TICK'

  return <SomeComponent {...{ someTitle, TICK }} />
}

link codesandbox 链接代码框

TICK is not underlined in red and the linter will not pick up the error TICK 没有红色下划线,linter 不会拾取错误

This is a behaviour present with TS without React too.这也是没有 React 的 TS 存在的行为。

Take the below example:举个例子:

const split = { a : 1 , b : 2};
const func = ({a } :{ a : number}) => {
    console.log(a);
};
func(split)

TS will not complain about the above. TS不会抱怨以上的。 You might be passing extra keys into the object, but as long as you are passing the mandatory keys it works.您可能会将额外的键传递给对象,但只要您传递必需的键,它就可以工作。

Take this example now:现在举这个例子:

const split3 = { a : 1 };
const split2 = { x : 1};
const func2 = ({x ,a} :{ x : number, a: number}) => {
    console.log(x);
};

func2(split)
func2(split2)

Both the above statements will be errored out by TS as both x and a are not provided and only one of them is.上述两个语句都会被 TS 错误输出,因为x 和 a都没有提供,只有其中一个提供了。

Demo 演示

props is also one of the arugments passed the function al component, and it will not error out when extra keys are passed into any of its object. props也是传递给函数al 组件的参数之一,当额外的键传递给它的任何对象时,它不会出错。 The extra properties of an object are not checked in most cases.在大多数情况下,不会检查对象的额外属性。

Note: Excess properties are still checked when you are assigning object literal.注意:在分配对象字面量时,仍会检查多余的属性。 Below will throw an error: 下面会报错:

interface test{ 
    a: number;
}

let x : test = {
    a: 1,
    b: 2,
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM