Q:

TypeScript: Declare Intersection Type with Symbol?

I am currently writing a helper function, that adds a Symbol to a value. 
function setSymbol<S extends symbol, T>(symbol: S, on: T, withValue: any = true): S & T { /*...*/ }

My problem here is, that I try to explain TypeScript that the result of this function is a value having the symbol-property, so I can do: 
const MySymbol = Symbol();
const value = {};

const resultWithSymbol = setSymbol(MySymbol, value);

resultWithSymbol[MySymbol] = true;

Is this possible? I played a bit with unique symbol but could not get it working. Thanks for your help!

A:

If you have any key type K and want to represent an object with that key and a value of type V, you can use the built-in Record<K, V> utility type like this:
function setSymbol<S extends symbol, T>(
  symbol: S, 
  on: T, 
  withValue: any = true
): Record<S, any> & T { 
    return null! // impl here
}

(You should determine from your use case whether Record<S, any> is good enough or if you want withValue to further narrow the type).  Note that Record<S, any> is the same as the mapped type {[K in S]: any} if you want to use that instead. You'll see that your example code works now:
const MySymbol = Symbol();
const value = {};
const resultWithSymbol = setSymbol(MySymbol, value);
resultWithSymbol[MySymbol] = true; // okay now
resultWithSymbol[Symbol("some other symbol")] = true; // error

Okay, hope that helps; good luck!
Link to code

