我刚开始使用typescript,我正在尝试将so代码从js迁移到ts,同时阅读ts HandBook。
下面是每个级别的开发人员和用户之间的关系:
lib developer -> ProductProvider ->产品开发人员-> Product ->产品用户-> robot
这看起来很顺利,除了我不知道如何告诉typescript机器人的类型,这是汇编函数返回值的类型,也是Product函数返回值的类型。
interface Injection {
[index: string]: string
}
interface Component {
id: string,
install: (injection: Injection) => void
}
interface InitOptions {
id: string,
screenType: string,
SoC: string,
components: Component[],
}
type Assembler = (injection: object, options: object) => unknown;
type ProductProvider = (initOptions: InitOptions, assembler: Assembler) => (options: object) => ReturnType<typeof assembler>
function ProductProvider(initOptions: InitOptions, assembler: Assembler): (options: object) => ReturnType<typeof assembler> {
//some work to init
const installedInjection: Injection = {};
initOptions.components.forEach((component => component.install(installedInjection)));
return function Product(startOption: object): ReturnType<typeof assembler> {
return assembler(installedInjection, startOption);
}
}
export default ProductProvider;
const assembler: Assembler = (injection: object, options: object) => ({ injection, options });
const Product = ProductProvider({
id: 'XMC9E8DCO5EXEU',
screenType: 'LCD',
SoC: 'RX-78',
components: [{
id: 'component1',
install(injection) {
//some work
const content = 'whatever';
injection[this.id] = content;
}
}]
}, assembler);
const robot = Product({ battery: 'A' });在Assembler类型中,因为ProductProvider的用户可以自由地进行汇编,所以我认为该函数的类型将返回unknown。
但实际上,产品开发人员知道传递给ProductProvider的汇编参数返回一个值,并且它的类型是object。
而其他产品开发人员也可能返回另一个接口或类型。
怎样才能让typescript类型系统知道返回值的类型?然后我们就可以享受智能感知了。
XD
发布于 2020-12-25 16:10:00
type Assembler<T> = (injection: object, options: object) => T;
type ProductProvider<T> = (initOptions: InitOptions, assembler: Assembler<T>) => (options: object) => T;好了。
https://stackoverflow.com/questions/65337267
复制相似问题