Check out this example of TypeScript code:
type Interpolation = null | undefined | boolean | number | string;
type DefaultTheme = {
color: {
primary: {
active: string;
default: string;
hover: string;
disabled: string;
background: string;
};
secondary: {
active: string;
default: string;
hover: string;
disabled: string;
background: string;
};
};
};
type Classes<K extends string> = {
[className in K]: string;
};
type Theme = DefaultTheme & {
[key: string]: any;
};
type DynamicStyle<K extends string> = (
theme: Theme,
deps: any[],
classes: Classes<K>,
) => Interpolation;
type Style<K extends string> = string | DynamicStyle<K>;
type Styles<K extends string> = ReadonlyArray<readonly [K, Style<K>]>;
function makeStyles<K extends string>(styles: Styles<K>) {
return styles;
}
makeStyles([
[
'tag',
(theme, [a, b, c]) => {
return '';
},
],
['label', ''],
]);
This could lead to an error:
Type 'string' is not assignable to type '"tag"'.
Note that the tag is '"tag"'
, which may be caused by TypeScript automatically inferring my type.
I prefer it to just be a plain string, not '"tag"'
.
Is there a way to ensure it stays as a string?
In other cases, TypeScript seemed to widen it to string automatically, so I am unsure why it behaves differently here.
https://i.sstatic.net/BtPwn.png https://i.sstatic.net/i6BaK.png
Also, here is my tsconfig file, and my TypeScript version is ^3.6.4
:
{
"include": ["src", "types", "test"],
"compilerOptions": {
"target": "es5",
"module": "esnext",
"lib": ["dom", "esnext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./",
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"baseUrl": "./",
"paths": {
"*": ["src/*", "node_modules/*"]
},
"jsx": "react",
"esModuleInterop": true
}
}