I am working on a node.js project and have created pseudo-enum elements using an object literal as below:
export const Relation = { OTHER: '', FRIEND: 'fr', ENEMY: 'en' }
In my code, I am using the enum elements like this:
if (player.relation === Relation.ENEMY)
I am using webpack for compiling my code and I would like to know how I can compile the above code to get something like this:
if (player.relation === 'en')
If there is no way to do that, I would like to not compile unused enum fields.
I would appreciate if someone could guide me on how to achieve this.
Related
Newbie Alert! I feel silly asking this question but I need someone to teach me the correct syntax.
I have code that looks like this:
let thing: INewThing;
thing.personId = another.personId;
thing.address = another.work.address;
thing.greades = another.subjectInfo.grades;
thing.isCurrent = another.student.isCurrent;
I know it can be written cleaner. I want to use a lamda expression, something like this:
let thing: INewThing => {
personId = another.personId,
address = another.work.address,
grades = another.subjectInfo.grades,
isCurrent = another.student.isCurrent
} as IThingUpdate;
I have looked and looked for an example. I have yet to find one that works for me. It's just syntax but no matter what I try it doesn't work.
You're just looking to create a new object, which is a pretty different thing from a "lambda" (function). Just declare the object. You don't need a function.
const thing = {
personId: another.personId,
address: another.work.address,
// use the correct spelling below - no 'greades'
grades: another.subjectInfo.grades,
isCurrent: another.student.isCurrent,
};
If the another is typed properly, that should be sufficient.
If the another object had more properties using the same path, another option would be to destructure those properties out, then declare the object with shorthand, eg:
const originalObj = { prop: 'val', nested: { foo: 'foo', bar: 'bar', unwanted: 'unwanted' } };
const { foo, bar } = originalObj.nested;
const thing = { foo, bar };
Destructuring like this, without putting the values into differently-named properties, helps reduce typos - if a property starts out, for example, as someLongPropertyName, putting it into a standalone identifier someLongPropertyName and then constructing an object with shorthand syntax ensures that the new object also has the exact property name someLongPropertyName (and not, for example, someLongPRopertyName - which isn't that uncommon of a mistake when using the more traditional object declaration format).
But since all the paths in your another object are different, this approach wouldn't work well in this particular situation.
I'm learning rust, and the best way to learn a programming language is obviously reading and understanding other's code. Now I faced this line I am not able to understand even after reading docs, other source files and googling for it :
In zoxide's main file, there's this line :
if let Err(e) = App::parse().run() { ... }
What does App::parse() mean ? App is a structure and not a variable, so I understand why it's not .parse(), but why ::parse() and what does it do ? (I couldn't find its definition in app's source code (nor in this file))
First, both the files you mentioned are not the App that zoxide is including. zoxide's main.rs file says use crate::app::{App, Run};, so it's including App from src/app/mod.rs, which exports App from src/app/_app.rs
In that file, we can see the declaration of App:
#[derive(Debug, Clap)]
#[clap(
bin_name = env!("CARGO_PKG_NAME"),
about,
author,
after_help = ENV_HELP,
global_setting(AppSettings::ColoredHelp),
global_setting(AppSettings::DisableHelpSubcommand),
global_setting(AppSettings::DisableVersionForSubcommands),
global_setting(AppSettings::PropagateVersion),
version = option_env!("ZOXIDE_VERSION").unwrap_or_default()
)]
pub enum App {
Add(Add),
Import(Import),
Init(Init),
Query(Query),
Remove(Remove),
}
The key in this case is #[derive(Clap)]. If you look at the clap crate you'll see that it's a crate for parsing command line parameters, and deriving from Clap adds a parse method to the structure.
We are trying to build a component with a property variant that should only be set to "primary" or "secondary" (enum). Currently, we are just declaring the attribute as a String, but we were wondering if there is a better way for handling enums? For example, should we validate somehow that the current value is part of the enum? Should we throw an error if not?
I asked this question on Slack and the answers I got lean towards declaring the property as String and use hasChanged() to display a warning in the console if the property value is invalid.
Standard HTML elements accept any string as attribute values and don't throw exceptions, so web components should probably behave the same way.
This all sounds reasonable to me.
If you're using TypeScript I'd recommend just using strings. You can use export type MyEnum = 'primary' | 'secondary' to declare it and then use #property() fooBar: MyEnum to get build time checking. You can use #ts-check to do this in plain JS with #type MyEnum too.
This works well if the enums are for component options or that map to server-side enums that will get validated again.
However, if you want to validate user input into enums or loop through them a lot this is less good. As the JS runs it has no visibility of the type. You need an object dictionary, something like:
const MyEnum = Object.freeze({
primary: 'primary',
secondary: 'secondary'
});
// Enforce type in TS
const value: keyof MyEnum;
// Validate
const validated = MyEnum[input.toLower()];
// Loop
for(const enumVal of Object.keys(MyEnum)) ...
// Or Convert to a different value type
const MyEnum = Object.freeze({
primary: 1,
secondary: 2
});
These are somewhat idiosyncratic. Again, if you're using TypeScript it has an enum keyword that compiles to something like this and I'd use that rather than rolling your own. Strings are the better option unless you need to validate, loop or convert the values.
I'm trying to work with shadow roots in my Testcafe project. It's a little bit complicated to deal with it. I create a custom function that behaves the same as Selector().find() but I struggle with this error :
The "boundTestRun" option value is expected to be a test controller.
when I'm doing as documented here :
import { Selector, t } from 'testcafe'
getInShadowRoot = Selector(
// More code here
)
const boundedGetInShadowRoot = this.getInShadowRoot.with({ boundTestRun: t })
I create a gist to illustrate my problem: https://gist.github.com/HugoDel/a600f3e120674e3f255884f3dc84fee3
Thanks for your help!
Edit:
I finally get rid of it since I don't need to add .with({ boundTestRun: t }) to make it work.
I have this TypeScript code:
import * as suman from 'suman';
const Test = suman.init(module,{
ioc: {
a: 'foo',
b: 'far'
} as suman.Ioc
});
As you can see I am trying to declare that the ioc object has a type of suman.Ioc (ioc object should "adhere to the Ioc interface"). But my IDE says "cannot find namespace 'suman'".
How can I create a type and reference it in my code in this scenario? I'd like to be able to reference the Ioc object type from the suman import if possible.
In other words, I don't want to do this all in the same file:
declare namespace suman {
interface Ioc {
a: string,
b: string
}
}
import * as suman from 'suman';
const Test = suman.init(module,{
ioc: {
a: 'foo',
b: 'far'
} as suman.Ioc
});
the reason is because I would then have to repeat the namespace declaration for every file like this which shouldn't be necessary (or advised).
suman is typed but the typed version is not release yet.
For now, you can installing it by npm install sumanjs/suman if you are comfortable to use the latest code.
If you want to use the latest release AND use the typings, you can consider using typings to install the typings file: typings install suman=github:sumanjs/suman/lib/index.d.ts and include typings/index.d.ts in your tsconfig.json.
As for as suman.Ioc, it is a way to tell the compiler that "hey, I know that you think this 'thing' is of some other type, but I would like you to treat it as 'suman.Ioc'".
That's why, even if the typings is there, it will not do what you wanted.
Luckily, the typings supplied by suman will be working fine for you.