Skip to content

Allow type 'any' be assignable to type 'unique symbol' #29108

Closed
@zheeeng

Description

@zheeeng

Search Terms

Type 'any' is not assignable to type 'unique symbol'.ts(2322)

Suggestion

Sometimes we just need a unique value for distinguishing whether a value is a specific unique value. Using an object instance meets this situation just like the Symbol does. Using Symbol requires the executing environment support ES6 Symbol, so we tend to use a simple replacement just like new String('simulate Symbol').

I propose allow us to assert an any type value to be unique symbol type.

const timeoutSignal: unique symbol = new String('@@timeoutSignal@@') as any    // tsc complains

At present, the TSC complains:

// Type 'any' is not assignable to type 'unique symbol'.ts(2322)

It's unlike the other primitive value type. I know it has runtime risk, but it is what the manually assert a type means for.

// not safe, but the types are compatible with the asserted type 'any' 
const fakeNumber: 42 = 'whatever' as any   // tsc allows us to assign 'any' type to 42 type
const fakeString: 'foo' = 'whatever' as any    // tsc allows us to assign 'any' type to 'foo' type

Use Cases

const timeoutSignal: unique symbol= new String('tiemout') as any
const haltSignal: unique symbol = new Number(1) as any

async function request <T>() {
    const ret = await Promise.race(
         sleep(5000).then(() => timeoutSignal),
         mayTriggerHaltSignalInAnyTime().then(() => haltSignal),
         requestRemoteData<T>(),
    )
    if (ret === timeoutSignal) {
           // retry
           return request<T>()
     }

      if (ret === haltSignal) {
          throw Error('Cancele by a halt signal')
      }

      return ret
}

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptGood First IssueWell scoped, documented and has the green lightHelp WantedYou can do this

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions