1

I see the following code in vue github link

declare const RefSymbol: unique symbol
export declare const RawSymbol: unique symbol

export interface Ref<T = any> {
  value: T
  
  [RefSymbol]: true
}

what is RefSymbol mean here? i have tried this code:

let test:Ref={value:1}

vscode tell me that I am missing attributes of [RefSymbol]

i had read these questions:

  1. stackoverflow link
  2. https://www.typescriptlang.org/docs/handbook/interfaces.html#indexable-types

some example code is

interface StringArray {
  [index: number]: string;
}
 
let myArray: StringArray;
myArray = ["Bob", "Fred"];
 
let myStr: string = myArray[0];

which is quite different with the first example code , it use:true rather than type :string , and i did not know how to pass value to [RefSymbol] ,can anyone explain this thing? thanks for any reply

  • Perfectly explained here already https://stackoverflow.com/questions/38404400/what-do-square-brackets-mean-where-a-field-should-be-in-typescript – DVN-Anakin Aug 04 '22 at 10:05
  • 1
    Does this answer your question? [What do square brackets mean where a field should be in typescript?](https://stackoverflow.com/questions/38404400/what-do-square-brackets-mean-where-a-field-should-be-in-typescript) – N.J.Dawson Aug 04 '22 at 10:23
  • It's possible to use `let test:Ref={value:1, [RefSymbol]: true}`. That also means that `test[RefSymbol]` will be true when you run it. (assuming it has been defined somewhere, e.g. `const RefSymbol = Symbol("key");`) – qrsngky Aug 04 '22 at 10:26

1 Answers1

1

oh it's a javascript declaration where RefSymbol is a constant. It's like this.

const key = "size"

const map = {
  [key]: 0
}

console.log(map[key]) // 0

typesccript declare also RefSymbol is declared as unique symbol which means it is a unique and invariant symbol set as key

Tachibana Shin
  • 2,605
  • 1
  • 5
  • 9
  • why i need to use `let test:Ref={value:1,[RefSymbol]:true}` when i create an instance of `Ref`? i think `RefSymbol` is already assign const `true`, i dont need to add it again, just like a function `void func(int a,int b=0)`,i can call `func(1)` and i dont need assign `b` because b has default value `0` – zhenghao li Aug 05 '22 at 03:19
  • You can not! Symbol is a special data type it cannot be recreated `Symbol("a") !== Symbol("a")` if you want to do so you must have access to the RefSymbol declared in the import and it – Tachibana Shin Aug 05 '22 at 07:43