繁体   English   中英

如何获取Typescript中通用参数的类型?

[英]How do I get the type of a generic parameter in Typescript?

我有这个助焊剂商店课程:

'use strict';
import flux = require('app/tools/flux');
import types = require('app/tools/types');
import Actions = require('app/actions/actions');

class Store
{
    bindListeners(config : any) : void {;};
    books : Array<types.IBook>;
    selectedBookName : string;

...
}

export = flux.createStore<Store>(Store, 'Store');

在此视图中使用了该方法:

"use strict";
import React = require('react');
import Store = require('app/stores/store'); // <-- here we import the Store
import _ = require('lodash');
import BookHelper = require('app/tools/bookHelper');
import Msg = require('app/tools/messages');

interface props {}
interface state {}

class NoteContainer extends React.Component<props, state>
{
    state: typeof Store; // <-- this is Altjs<Store>, not Store :(

    render()
    {
        if (!this.state.selectedBookName)  // <-- here's an error
            return;
...

这给出了编译错误:

error TS2339: Property 'selectedBookName' does not exist on type 'AltStore<Store>'.

如何将视图的状态设置为实际的Store类,而不是AltStore<Store>类? 即如何获取通用参数的类型,如下所示: state: typeof Store<THIS THING>

state参数只是编译器的类型参数。 它在运行时不可用,它就在那里,以便可以对诸如setState之类的方法进行类型检查。 但是,您将从代码中导出商店的实例,而不是商店类型本身。 因此,您想将其分配给构造函数中的state属性。 还要注意,状态类型必须是普通的JS对象-React将在运行时在状态对象上使用Object.assign,如果不是普通对象,则会引起问题。 像这样:

import storeInstance = require('app/stores/store');

interface StateType {
    store: AltStore<Store>;
}
class NoteContainer extends React.Component<PropsType, StateType>
{
    constructor(props: PropsType) {
        super(props);
        this.state = {store: storeInstance};
    }

还要注意,您不需要指定state属性的类型,Component类定义中的type参数将为您处理。

我不确定要像您在此处那样从模块中导出实例,我无法使其正常工作,但我没有使用require样式导入。 如果它不起作用,则可能需要将其包装在一个返回实例并导出该函数的函数中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM