如何用Typescript定义组件、函数(几个例子)

173 阅读1分钟

1、函数组件(普通函数)

export function ContextProviders<T extends Array<LiteStoreContractor<any, any, any>>>({
  stores,
  children,
}: React.PropsWithChildren<{ stores: T }>): JSX.Element {
  const [store, ...restStores] = stores;
  const { ContextProvider } = useContextStore(store);

  return (
    <ContextProvider>
      {restStores.length ? <ContextProviders stores={restStores}>{children}</ContextProviders> : children}
    </ContextProvider>
  );
}

2、使用React.CSSProperties定义style

例如我想指定一个div的宽和高,可以用以下方式定义style:

const divStyle: React.CSSProperties = {
    width: "11rem",
    height: "7rem",
    backgroundColor: `rgb(${props.color.red},${props.color.green}, ${props.color.blue})`
  };

那么,如何使用这个style呢?换句话说,如何使用divStyle这个变量呢?

<div style={divStyle} />

以上方式其实定义了一个divStyle变量,然后把一个对象赋值给该变量,然后把某个div的style属性指定为该对象即可。还有另外一种方法,定义一个函数,执行该函数return一个CSS对象。

你可以看出,divStyle是一个函数,他会根据props的不同,返回不同的css对象。

interface SidebarProps {
    isVisible: boolean;
}
const divStyle = (props: SidebarProps): React.CSSProperties=>({
    width: props.isVisible ? "23rem" : "0rem"
})

那么如何使用该函数,参考如下方法:

export const SidebarComponent: React.StatelessComponent<SidebarProps> = props => (
    <div style={divStyle(props)}>
    {props.isVisible}
    </div>
)

3、如何定义Promise、async的类型

其返回值是Promise类型,<>内是传给resolve()的参数类型。

async function getArticle(): Promise<{ data: string; time: number }> {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve({
                data: Mock.mock('@paragraph'),
                time: new Date().getTime(),
            });
        }, 1000);
    });
}

如果resolve内是空的,如何定义函数?

function generateName(): Promise<{ success: boolean }> {
  return new Promise(resolve => {
    setTimeout(() => {
      const name = Mock.mock('@name');
      Message.success(`请求成功,生成的 Name 是 ${name}`);
      resolve();
    }, 1000);
  });
}

4、定义对象,且指定key和value类型

image.png

5、 预先定义的条件类型( Predefined conditional types )

-   Exclude<T, U> - 用于从类型T中去除不在U类型中的成员
-   Extract<T, U> - 用于从类型T中取出可分配给U类型的成员
-   NonNullable<T> - 用于从类型T中去除undefinednull类型
-   ReturnType<T> - 获取函数类型的返回类型
-   InstanceType<T> - 获取构造函数的实例类型

zhuanlan.zhihu.com/p/52662645