TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

String literal types as index signature parameter types?

Open mariusschulz opened this issue 11 years ago • 73 comments

According to https://github.com/Microsoft/TypeScript/pull/5185, string literal types are assignable to plain strings. Given the following type definition:

type NodeType = "IfStatement"
              | "WhileStatement"
              | "ForStatement";

Both these assignments are valid:

const nodeType1: NodeType = "IfStatement";
const nodeType2: string = nodeType1;

However, string literal types currently can't be used as index signature parameter types. Therefore, the compiler complains about the following code:

let keywords: { [index: NodeType]: string } = {
    "IfStatement": "if",
    "WhileStatement": "while",
    "ForStatement": "for"
};

// error TS1023: An index signature parameter type must be 'string' or 'number'.

Shouldn't that scenario be supported, given that string literal types are assignable to strings?

/cc @DanielRosenwasser

mariusschulz avatar Nov 16 '15 14:11 mariusschulz

I've looked over this thread, and I'm a little confused. Why does this work:

type Point<D extends string> = {
  [key in D]: number;
}

but this does not?

interface Point<D extends string> { 
  [key in D]: number 
}

image

It seems to me that the two should be equivalent. What am I missing?

joeskeen avatar Sep 18 '19 18:09 joeskeen

Perhaps you could post an example of what you're after here as what you're showing here is wanting each key in a string. Not typical.

If you have a point that has say x and y

const point = {
  x: 100,
  y: 200
}

Then you'd have a type something like this:

interface IPoint {
  x: number;
  y: number;
}
type PointKeys = keyof IPoint;

But again maybe post a little more of what you're after here.

blujedis avatar Sep 18 '19 18:09 blujedis

Or maybe you're after something like this:

interface IPoint {
  x: number;
  y: number;
}

const points = {
  one: { x: 100, y: 200 },
  two: { x: 200, y: 300 }
};

type PointKeys = keyof typeof points;

type Points = { [K in PointKeys]: IPoint };

blujedis avatar Sep 18 '19 18:09 blujedis

What I've been trying to express is a Point with an arbitrary number of named dimensions. For example:

const point2D: Point<'x' | 'y'> = {x: 2, y: 4};
const point6D: Point<'u' | 'v' | 'w' | 'x' | 'y' | 'z'> = {
  u: 0,
  v: 1,
  w: 2,
  x: 3,
  y: 4,
  z: 5
};

But I think my use case isn't as important as the question of why the index signature works in a type alias but not in an interface?

I just spent a long time trying to get it to work as an interface before realizing that the same thing as a type alias works. It's a little confusing why one would work but not the other.

joeskeen avatar Sep 18 '19 19:09 joeskeen

I see, I misunderstood you're not asking for a solution but the why?

So this works just fine, I'm assuming you realized that but to be clear:

type Point<Keys extends string> = { [K in Keys]: number };

const point2D: Point<'x' | 'y'> = {x: 2, y: 4};

const point6D: Point<'u' | 'v' | 'w' | 'x' | 'y' | 'z'> = {
  u: 0,
  v: 1,
  w: 2,
  x: 3,
  y: 4,
  z: 5
};

Unlike the type alias which is enumerating the keys an interface is a definition hence the generic type would have to be an object or a Symbol. So what you're trying to do here needs to be done with a type alias as you're not defining it but rather representing what it is based on the keys. Think of it like a Record<T, K extends string> if that makes sense.

blujedis avatar Sep 18 '19 19:09 blujedis

I think index signature parameter should also allow for the String type and sub-types because it is valid. I need this for the scenario I've explained here: https://github.com/microsoft/TypeScript/issues/6579#issuecomment-537306546

omidkrad avatar Oct 04 '19 21:10 omidkrad

@mariusschulz, how about let keywords: { [key in keyof NodeType]: string }?

MajidJafari avatar Oct 05 '19 12:10 MajidJafari

@mariusschulz, how about let keywords: { [key in keyof NodeType]: string }?

I don't think it makes sense, keyof NodeType will give you different literal strings - methods on String type.

What I tend to do is to reverse the problem, usually it's enough for my cases:

interface KeywordsMappings  {
  IfStatement: "if", // or string if you want to widen the type
  WhileStatement: "while",
  ForStatement: "for"
}

type Keywords = keyof KeywordsMappings

let keywords: KeywordsMappings = {
    "IfStatement": "if",
    "WhileStatement": "while",
    "ForStatement": "for"
};

apieceofbart avatar Nov 20 '19 15:11 apieceofbart

Not sure what happens but I guess it's a similar problem:

type TestMap<T extends string> = {[key in T]: string}

const a = <T extends string>(aa: T) => {
    const x: TestMap<T> = {
        [aa]: 'string'
    }
}

//Type '{ [x: string]: string; }' is not assignable to type 'TestMap<T>'.(2322)

SanCoder-Q avatar Dec 05 '19 04:12 SanCoder-Q

We can achieve this by using Record :

type NodeType = 'IfStatement' | 'WhileStatement' | 'ForStatement'
type NodeTypeObject = Record<NodeType, string>

// works!
var myNodeTypeObject: NodeTypeObject = {
  IfStatement: 'if',
  WhileStatement: 'while',
  ForStatement: 'for',
}

// complains if there are missing proeprties
var myNodeTypeObject: NodeTypeObject = {
  IfStatement: 'if',
  WhileStatement: 'while',
} // --> Error : Property 'ForStatement' is missing but required by type 'Record<NodeType, string>'.

// Complains if additional properties are found
var myNodeTypeObject: NodeTypeObject = {
  IfStatement: 'if',
  WhileStatement: 'while',
  ForStatement: 'for',
  foo :'bar'  // --> Error :  'foo' does not exist in type 'Record<NodeType, string>'.
}

Bonus: If we want the properties to be optional we can do it by using Partial:

type NodeType = 'IfStatement' | 'WhileStatement' | 'ForStatement'
type NodeTypeObject = Partial<Record<NodeType, string>>

// works!
var myNodeTypeObject: NodeTypeObject = {
  IfStatement: 'if',
  WhileStatement: 'while',
}

try it in the typescript playground

colxi avatar Jan 19 '20 19:01 colxi

But in this solution your cannot iterate the keys:


type NodeType = 'IfStatement' | 'WhileStatement' | 'ForStatement'
type NodeTypeObject = Record<NodeType, string>

// works
var myNodeTypeObject: NodeTypeObject = {
  IfStatement: 'if',
  WhileStatement: 'while',
  ForStatement: 'for',
}

function getNameFromValue(str: string): NodeType | undefined {
  for (const k in myNodeTypeObject){
    if (myNodeTypeObject[k] === str) { // any
      return k; // is a string
    }
  }
}

Playground

https://github.com/microsoft/TypeScript/issues/5683#issuecomment-515744911

LukasBombach avatar Jan 20 '20 08:01 LukasBombach

If we allow template literal types to be used as index signature parameter types, then we could do something like this to let CSS variables be assignable to the React style prop:

type CSSVariable = `--${string}`;

interface CSSProperties {
  [index: CSSVariable]: any;
}

// ...

<div style={{ '--color-text': 'black' }}>{/* ... */}</div>

loqusion avatar May 19 '21 06:05 loqusion

Same thing happens in Vue. Volar provides type checking in Vue templates, but the following template is currently an error:

<div :style="{ '--color-text': 'black' }" />

To fix this in a generic way we need to have the template literal type CSSVariable in interface CSSProperties as shown by @Flandre-X in previous comment.

jods4 avatar Jun 10 '21 16:06 jods4