type CarNames = 'bmw' | 'mercedes';
const cars: CarNames[] = ['bmw', 'mercedes', 'zhiguli'];
// ^^^^^^^
// TypeError: Type '"zhiguli"' is not assignable to type 'CarNames'.
const data: {
hello: {
wtf: string;
};
} = {
hello: {
wtf: 'world',
},
};
for (const [key] of Object.entries(data) as [keyof typeof data, any][]) {
console.log(data[key]);
}
interface Data {
hello: {
wtf: string;
};
}
type DataKey = keyof Data;
const data: Data = {
hello: {
wtf: 'world',
},
};
for (const [key] of Object.entries(data) as [DataKey, any][]) {
console.log(data[key]);
}
// webpack.config
module.exports = {
module: {
rules: [
{
oneOf: [
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
options: {
cacheDirectory: true,
},
},
{
use: 'file-loader',
exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
],
},
plugins: [
new ForkTsCheckerWebpackPlugin({
async: true,
useTypescriptIncrementalApi: true,
checkSyntacticErrors: true,
eslint: true,
}),
],
};
// babelrc
{
"presets": [
"@babel/preset-env",
"@babel/preset-typescript"
],
}
addToCart = (id: number) => {
let tempProduct: Products[] = [...this.state.products];
const item = this.getItem(id);
if(item === undefined) {
// ... инструкция при возникновении терминального условия, например, ошибка
return;
}
const index = tempProduct.indexOf(item as Products); // строгая типизация для item
// ...
};
getItem = (id: number): Products => {
return this.state.products.find(item => item.id === id);
};