首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >TypeScript中对象文字中的类型定义

TypeScript中对象文字中的类型定义
EN

Stack Overflow用户
提问于 2012-10-09 02:58:31
回答 14查看 447.7K关注 0票数 466

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

class className {
  property: string;
};

如何在对象文字中声明属性的类型?

我尝试了以下代码,但它不能编译:

var obj = {
  property: string;
};

我得到以下错误:

名称'string‘在当前作用域中不存在

是我做错了什么,还是这是个bug?

EN

回答 14

Stack Overflow用户

回答已采纳

发布于 2012-10-09 03:08:38

已经很接近了,只需要用:替换=即可。您可以使用对象类型文字(参见规范3.5.3节)或接口。使用对象类型文字与您所拥有的非常接近:

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

但是您也可以使用一个接口

interface MyObjLayout {
    property: string;
}

var obj: MyObjLayout = { property: "foo" };
票数 545
EN

Stack Overflow用户

发布于 2012-10-11 12:50:13

更新2019-05-15 (改进的Code Pattern作为替代方案)

在使用const多年并受益于更多的函数代码之后,我建议在大多数情况下不要使用下面的代码。(在构建对象时,强制将类型系统转换为特定类型,而不是让它推断类型,这通常是出了问题的迹象)。

相反,我建议尽可能多地使用const变量,然后将对象组合为最后一步:

const id = GetId();
const hasStarted = true;
...
const hasFinished = false;
...
return {hasStarted, hasFinished, id};

  • 这将正确地键入所有内容,而不需要任何显式类型。
  • 无需重新键入字段名称。
  • 这将导致my experience.
  • This中最干净的代码允许编译器提供更多的状态验证(例如,如果您在多个位置返回,编译器将确保始终返回相同类型的对象-这鼓励您在每个位置声明整个返回值-给出该值的一个非常清晰的意图)。

相加2020-02-26

如果您确实需要一个可以延迟初始化的类型:请标记它是一个可以为null的联合类型(null或Type)。类型系统将阻止您在未首先确保它具有值的情况下使用它。

tsconfig.json中,确保启用严格的null检查:

"strictNullChecks": true

然后使用此模式,并允许类型系统保护您免受意外的空/未定义访问:

const state = {
    instance: null as null | ApiService,
    // OR
    // instance: undefined as undefined | ApiService,

};

const useApi = () => {
    // If I try to use it here, the type system requires a safe way to access it

    // Simple lazy-initialization 
    const api = state?.instance ?? (state.instance = new ApiService());
    api.fun();

    // Also here are some ways to only access it if it has value:

    // The 'right' way: Typescript 3.7 required
    state.instance?.fun();

    // Or the old way: If you are stuck before Typescript 3.7
    state.instance && state.instance.fun();

    // Or the long winded way because the above just feels weird
    if (state.instance) { state.instance.fun(); }

    // Or the I came from C and can't check for nulls like they are booleans way
    if (state.instance != null) { state.instance.fun(); }

    // Or the I came from C and can't check for nulls like they are booleans 
    // AND I was told to always use triple === in javascript even with null checks way
    if (state.instance !== null && state.instance !== undefined) { state.instance.fun(); }
};

class ApiService {
    fun() {
        // Do something useful here
    }
}

在99%的情况下,不要执行以下操作:

更新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,
};

原始答案

使用cast操作符使其简洁(通过将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,
};
票数 341
EN

Stack Overflow用户

发布于 2019-05-20 16:56:05

我很惊讶没有人提到这一点,但您可以只创建一个名为ObjectLiteral的接口,它接受类型为string: anykey: value

interface ObjectLiteral {
  [key: string]: any;
}

然后使用它,如下所示:

let data: ObjectLiteral = {
  hello: "world",
  goodbye: 1,
  // ...
};

一个额外的好处是,您可以根据需要在任意多个对象上多次重用此接口。

祝好运。

票数 64
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12787781

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档