Typescript 里的这种写法是什么意思?

2021-01-22 13:45:02 +08:00
 tsuih

在看源码的时候发现下面这种写法,不明白是什么意思,请教一下各位:

const temp: ToughCookieFileStore = {
    [domain]: {
        [path]: {
            [name]: {
                key: name,
                value: etcCookie.value,
                expires,
                domain,
                path,
                secure: etcCookie.secure,
                httpOnly: etcCookie.httpOnly,
                hostOnly: etcCookie.hostOnly,
            },
        },
    },
};

下面是接口的声明

 export interface ToughCookieFileStore {
  [site: string]: TCFSPaths;
}

export interface TCFSPaths {
  [site: string]: TCFSCookies;
}

export interface TCFSCookies {
  [cookieName: string]: TCFSCookieAttributes;
}

export interface TCFSCookieAttributes {
  key: string;
  value: string;
  expires?: string;
  maxAge?: number;
  domain: string;
  path: string;
  secure?: boolean;
  httpOnly?: boolean;
  extensions?: string[];
  hostOnly: boolean;
  creation?: string;
  lastAccessed?: string;
}
1997 次点击
所在节点    TypeScript
5 条回复
CismonX
2021-01-22 13:55:27 +08:00
noe132
2021-01-22 15:50:24 +08:00
domain 是变量,用 domain 的值做 key 。方括号内可以是任意表达式

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer

不要被 ts 骗了,这是 js 的语法
alexkuang
2021-01-22 17:12:28 +08:00
方括号里是对象的动态键名,es6 语法跟 ts 无关
bearboss
2021-01-22 17:31:56 +08:00
索引签名,外面两层实际上并没有什么限制,可以设置任意的字符串作为属性,最后这层才需要符合 TCFSCookieAttributes 的定义
tsuih
2021-01-25 13:59:56 +08:00
@noe132 多谢,很有帮助

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/747372

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX