由于TypeScript改进了v3.2中的JSX类型检查,我们现在有一个问题就是正确键入我们的HOC.
有人可以在TypeScript 3.2的以下HOC中修复类型吗?
import { ComponentType } from 'react';
type Props = { custom: string };
type Omit<T, K extends string> = Pick<T, Exclude<keyof T, K>>;
function hoc<P extends Props>(Component: ComponentType<P>) {
return (props: Omit<P, keyof Props>) => {
return <Component {...props} custom="text" />;
}
}
Run Code Online (Sandbox Code Playgroud)
TypeScript错误:
Type '{ custom: string; }' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
Property 'custom' does not exist on type 'IntrinsicAttributes & P & { children?: ReactNode; }' …Run Code Online (Sandbox Code Playgroud) 我们使用Babel来编译我们的TypeScript文件,我们想在tsconfig.json中使用isolatedModules:true,因为它是推荐的方式.例如,当您尝试重新导出接口时,它会引发错误.这是一个必要的功能,因为Babel TypeScript编译器也不允许这样做.
但是,我们需要在TS文件中导入JSON文件.问题是tsc会抛出以下错误:
Cannot compile namespaces when the '--isolatedModules' flag is provided.
Run Code Online (Sandbox Code Playgroud)
知道如何导入JSON并保持类型检查器满意吗?
我们正在尝试使用Typescript的monorepo方法(Yarn的工作空间).
例如,我们有两个库:@project/main和@project/common.
每个库中的tsconfig.json如下所示:
{
...
"baseUrl": "./"
}
Run Code Online (Sandbox Code Playgroud)
这允许我们在每个库中使用绝对导入.
现在假定,一个index.ts在@项目/主库包含:
import { foo } from "@project/common";
Run Code Online (Sandbox Code Playgroud)
和index.ts在@项目/通用包含:
export * from "src/functions";
Run Code Online (Sandbox Code Playgroud)
在@ project/main的类型检查/编译期间,Typescript将尝试在@ project/main/src/functions.ts中找到一个foo函数,而不是@ project/common/src/functions.ts
这是因为Typescript将正确地遵循"@ project/common"导入,然后,它将尝试遵循"src/functions"导出.然而,这种进口是绝对的,所以打字稿将使用的baseUrl,这是领导对"@计划/主".
为了解决这个问题,我们可以添加如下内容:
{
"paths": {
"*": [
"*",
"../../node_modules/@project/common/*"
]
}
},
Run Code Online (Sandbox Code Playgroud)
到" @project/main"包的tsconfig.json.
这可以解决我们的问题,直到我们将一个functions.ts文件添加到主项目(@project/main/src/functions.ts).
现在,打字稿将使用functions.ts从@项目/主,而不是@项目/常见,这显然是一个不被接受的行为.
所以,我的问题是:是否有可能配置一个打字稿使用 …
由于 TypeScript 现在支持模板文字类型,是否可以有类似以下内容?
interface Data {
a: number;
b: {
c: number;
d: number;
}
}
type OmitDeep<T, K> = ...
type WithoutC = OmitDeep<Data, 'b.c'>
Run Code Online (Sandbox Code Playgroud)
其中WithoutC将被推断为:
interface WithoutC {
a: number;
b: {
d: number
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个简单的问题:是否可以在 TypeScript 中获取联合的一部分的类型?
例如,您可以经常使用这样的查找类型:
interface Person {
name: string;
}
type Name = Person['name']
Run Code Online (Sandbox Code Playgroud)
现在,我假设这样的工会是不可能的:
type Entity =
{ __type: 'Company', name: string }
| { __type: 'Employee', firstName: string };
Run Code Online (Sandbox Code Playgroud)
那么,有没有什么办法可以获取工会的一部分呢?像这样的东西:
type Company = DoTheMagic<Entity, { __type: 'Employee' }>
const company: Company = ...;
console.log(company.name) // OK
console.log(company.firstName) // Compile error
Run Code Online (Sandbox Code Playgroud)