相关疑难解决方法(0)

Typescript React:访问组件属性类型

npm包@types/react允许我们在TypeScript应用程序中使用React.我们将组件定义为

type Props = {...}

type State = {...}

export default class MyComponent extends React.Component<Props, State> {
}
Run Code Online (Sandbox Code Playgroud)

这里我们必须声明组件props和state的类型(在类型变量中).

在我们声明了类型之后,TypeScript使用它来验证组件的使用(传递给它的props的形状).

我想围绕这样一个组件创建一个容器.容器将重用组件的props.但是为了创建具有相同道具的另一个组件,我必须再次重新声明道具的类型.或者从原始组件文件中导出它们并导入到容器中:

// original file
export type Props = {...}

// container file
import MyComponent, { Props } from './original'
Run Code Online (Sandbox Code Playgroud)

但我已经MyComponent从该文件导入了.此组件已包含有关其消耗的道具的信息(感谢类型变量React.Component).

问题是如何从组件类本身访问该信息而不显式导出/导入props的类型

我想要的东西:

import MyComponent from './MyComponent'

type Props = MyComponent.Props // <= here access the component prop types

export default class MyContainer extends React.Component<Props, {}> {}
Run Code Online (Sandbox Code Playgroud)

typescript reactjs

24
推荐指数
4
解决办法
1万
查看次数

如何在打字稿中获取异步函数的返回类型?

考虑我们有一个如下所示的函数

const upper = (str: string) : string => string.toUpperCase() 
Run Code Online (Sandbox Code Playgroud)

我们可以使用以下方法获取函数的类型ReturnType

type Test = ReturnType<typeof upper>
Run Code Online (Sandbox Code Playgroud)

但现在考虑我们有一个异步函数。

const getUserData = async (uid: string): Promise<{name: string, email: string}> => {
   ...
};
Run Code Online (Sandbox Code Playgroud)

现在我们怎样才能得到这种类型{name: string, email: string}

javascript typescript

16
推荐指数
2
解决办法
7626
查看次数

获取通用参数的类型

我写了一个小函数,以便更好地处理类型.

function evaluate(variable: any, type: string): any {
    switch (type)
    {
        case 'string': return String(variable);
        case 'number': return isNumber(variable) ? Number(variable) : -1;
        case 'boolean': {
            if (typeof variable === 'boolean')
                return variable;

            if (typeof variable === 'string')
                return (<string>variable).toLowerCase() === 'true';

            if (typeof variable === 'number')
                return variable !== 0;

            return false;
        }
        default: return null;
    }
}

function isNumber(n: any): boolean {
    return !isNaN(parseFloat(n)) && isFinite(n);
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用泛型,但不知道如何从泛型参数获取类型.这是可能的?

generics types typescript

11
推荐指数
2
解决办法
2万
查看次数

标签 统计

typescript ×3

generics ×1

javascript ×1

reactjs ×1

types ×1