Skip to main content

实战

常用语法:解构别名类型限制

在用 TypeScript 开发时需要解构一个对象。

在结构时我是这样做的:

const { name, age } = body.value
我想为这两个属性定义类型:

const { name: string, age: number } = body.value
但是这样会有问题。虽然能工作,但是实际上把 name 属性赋值给了 string 变量,把 age 属性赋值给了 number 变量。

正确的语法是这样的:
const { name, age }: { name: string; age: number } = body.value


最好的方式是为此类数据定义一个类型:
interface Dog {
name: string
age: number
}
这样写会更简单:
const dog: Dog = body.value

interface限制函数

父组件:
const modalSwitch = (visible: boolean) => {
console.log("modalSwitch")
setDeptModalVisible(visible)
}

<DeptModal visible={deptModalVisible} modalSwitch={modalSwitch} />

子:
interface DeptModalType {
visible: boolean
modalSwitch(visible: boolean): void
onOpen?(): void
onClose?(): void
}

const DeptModal: FC<DeptModalType> = (props) => {
...
}

实例:react props.children包装

interface chartsContainerProps {
children: React.ReactNode
showLoading?: boolean
showError?: string
}
const ChartsContainer = (props: chartsContainerProps) => {
const { showLoading = true, showError = '' } = props
return (
<>
{props.children}
</>
)
}
export default ChartsContainer

event ts警告

function ChildComponent(props: any) {
function handleClick(event: React.MouseEvent<HTMLDivElement, MouseEvent>) {
event.stopPropagation?.();
// 处理点击事件
}

return (
<div onClick={handleClick}>
子组件
</div>
);
}