MST

星途 面试题库

面试题:Qwik 组件Props类型定义基础

在Qwik中,假设你有一个组件接收一个代表用户年龄的prop,如何使用TypeScript对这个prop进行类型定义和基本的范围验证(年龄需大于0且小于120)?请给出代码示例。
39.1万 热度难度
前端开发Qwik

知识考点

AI 面试

面试题答案

一键面试

在Qwik组件中,可如下使用TypeScript对接收的用户年龄prop进行类型定义和范围验证:

import { component$, useSignal } from '@builder.io/qwik';

interface Props {
  age: number;
}

export const MyComponent = component$<Props>(({ age }) => {
  if (age <= 0 || age >= 120) {
    throw new Error('Age must be greater than 0 and less than 120');
  }

  return (
    <div>
      User's age is: {age}
    </div>
  );
});

在上述代码中:

  1. 首先定义了一个 Props 接口,用于对组件接收的props进行类型定义,这里定义了 agenumber 类型。
  2. 在组件函数内部,通过 if 语句对 age 进行范围验证,如果不满足大于0且小于120的条件,抛出一个错误。