首页 文章

在TypeScript中的对象文字中键入定义

提问于
浏览
201

在类中的TypeScript中,可以为属性声明类型,例如:

class className{
    property : string;
};

我应该如何编写代码来声明对象文字中的属性类型?这样的代码不编译:

var obj = {
    property: string;
};

(我收到错误 - 当前范围中不存在名称'string') .

我做错了什么或者是一个错误?

4 回答

  • 10

    你非常接近,你只需要用 : 替换 = . 您可以使用对象类型文字(请参阅规范第3.5.3节)或界面 . 使用对象类型文字与您拥有的文字很接近:

    var obj: { property: string; } = { property: "foo" };
    

    但您也可以使用界面

    interface MyObjLayout {
        property: string;
    }
    
    var obj: MyObjLayout = { property: "foo" };
    
  • 5

    使用强制转换操作符来简化(通过将null转换为所需的类型) .

    var obj = {
        property: <string> null
    };
    

    一个较长的例子:

    var call = {
        hasStarted: <boolean> null,
        hasFinished: <boolean> null,
        id: <number> null,
    };
    

    这比有两个部分要好得多(一个用于声明类型,第二个用于声明默认值):

    var callVerbose: {
        hasStarted: boolean;
        hasFinished: boolean;
        id: number;
    } = {
        hasStarted: null,
        hasFinished: null,
        id: null,
    };
    

    更新2016-02-10 - 处理TSX(谢谢@Josh)

    使用TSX的as运算符 .

    var obj = {
        property: null as string
    };
    

    一个较长的例子:

    var call = {
        hasStarted: null as boolean,
        hasFinished: null as boolean,
        id: null as number,
    };
    
  • 175

    如果您正在尝试编写类型注释,则语法为:

    var x: { property: string; } = ...;
    

    如果您正在尝试编写对象文字,则语法为:

    var x = { property: 'hello' };
    

    您的代码正在尝试在值位置使用类型名称 .

  • 272

    在打字稿中,如果我们声明对象那么

    [access modifier]变量名:{//对象结构}

    private Object:{Key1:string , Key2:number }
    

相关问题