V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
tsuih

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

  •  
  •   tsuih · Jan 22, 2021 · 2891 views
    This topic created in 1931 days ago, the information mentioned may be changed or developed.

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

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

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

    不要被 ts 骗了,这是 js 的语法
    alexkuang
        3
    alexkuang  
       Jan 22, 2021 via iPhone
    方括号里是对象的动态键名,es6 语法跟 ts 无关
    bearboss
        4
    bearboss  
       Jan 22, 2021
    索引签名,外面两层实际上并没有什么限制,可以设置任意的字符串作为属性,最后这层才需要符合 TCFSCookieAttributes 的定义
    tsuih
        5
    tsuih  
    OP
       Jan 25, 2021
    @noe132 多谢,很有帮助
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5818 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 02:42 · PVG 10:42 · LAX 19:42 · JFK 22:42
    ♥ Do have faith in what you're doing.