V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
tsuih
V2EX  ›  TypeScript

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

  •  
  •   tsuih · 2021-01-22 13:45:02 +08:00 · 1966 次点击
    这是一个创建于 1161 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    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;
    }
    
    5 条回复    2021-01-25 13:59:56 +08:00
    noe132
        2
    noe132  
       2021-01-22 15:50:24 +08:00 via Android
    domain 是变量,用 domain 的值做 key 。方括号内可以是任意表达式

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

    不要被 ts 骗了,这是 js 的语法
    alexkuang
        3
    alexkuang  
       2021-01-22 17:12:28 +08:00 via iPhone
    方括号里是对象的动态键名,es6 语法跟 ts 无关
    bearboss
        4
    bearboss  
       2021-01-22 17:31:56 +08:00
    索引签名,外面两层实际上并没有什么限制,可以设置任意的字符串作为属性,最后这层才需要符合 TCFSCookieAttributes 的定义
    tsuih
        5
    tsuih  
    OP
       2021-01-25 13:59:56 +08:00
    @noe132 多谢,很有帮助
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4223 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 05:29 · PVG 13:29 · LAX 22:29 · JFK 01:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.