Stop Using {} In TypeScript
ฝัง
- เผยแพร่เมื่อ 16 ส.ค. 2023
- 🌎 Find Me Here:
My Blog: blog.webdevsimplified.com
My Courses: courses.webdevsimplified.com
Patreon: / webdevsimplified
Twitter: / devsimplified
Discord: / discord
GitHub: github.com/WebDevSimplified
CodePen: codepen.io/WebDevSimplified
#Shorts
Type-safe language programmers:
"Look what they need just to mimic a fraction of our power."
hate from javascript developer
In all fairness, strict TS is almost like Java, as long as you dont use "any" or some stupid typing. We can just ignore the typing and if you don't do weird things you'll almost always get the correct type inferred, specially with the latest versions of TS. TS is not JS
You ain't building no web UI with those type safe languages tho
I name it key instead of index.
{ [key:string] : unknown }
Makes more sense. I thought it had to be named index.
I'd also use key or property but index should be just fine as it stands for index signature
Same thing but I use the Record syntax instead. Kinda more pleasing to look at
And it works
Same here 👌
For a split second I read "Stop using TypeScript"
And that would have been good advice.
@@FkDJT-ut1hm why?
@@teawrld5976 he has been paralysed by fear
you should mention the `object` (note lowercase) this is the most generic pure object you can specify, usually useful it you're extended a generic. function foo (bar: T) { return Object.keys(bar) }
thanks kyle, keep with the snippets of TS
also you can do `Record`
`PropertyKey` shorthand for `string | symbol | number`
The title made me think for a moment there was a trick in TS to get rid of the block scope delimiters "{" "}" lol
Me watching this even though I know nothing about coding: Very nice
No better time to start
@@IAmLeslehI think this person wants to finish, not start 😏
Fuck typescript
You should try coding
@@IAmLeslehactually it's the worst time to start
Thank you so much Kyle! I've been struggling to type the ioredis georadius result. This will help me
These shorts are awesome, goat js/ts content creator
Record won't exclude arrays though.
If you want to exclude arrays, you'll need to do `Record`.
There are a few small corner cases where `Record` is too strict, but those don't come up much in user-land.
You sure?
type personData = Record;
// This will cause a TypeScript error because it doesn't match the declared type
function f(obj: personData) {
return obj;
}
f(["3"])
// Argument of type 'string[]' is not assignable to parameter of type 'personData'.Index signature for type 'string' is missing in type 'string[]'.ts(2345)
I assumed you’d be putting the type in a generic (which is usually what you want - if your use case looks like that, it’s probably fine to just use `object` and allow arrays)
how tf are you supposed to make an array with string indexes?
@@theefeoldit's not that arrays have string indexes, it's that arrays have methods, and methods are strings. The symbol trick is a hack that only works because it takes advantage of how index signatures work in the TS type system -- and it's not bulletproof. An interface declared that way -- interface MyInterface { [x: symbol]: unknown } will behave* differently (unfortunately)
Super helpful! Relaxes my brain to think of it this way
Deno helped me a lot to learn TypeScript and avoid some bad practices such as this one
One could just type it like this:
type Obj = {
name: string;
surname: string;
};
Record is only needed if you want to build a versatile function that handles different objects with the same structure or if you expect an object from an API f.ex. to change property names in the future
You can't pass any object with the type you defined. Thats the whole point of this short.
@@IStMl Isn't date an object..
The point of this short is specifically to allow objects where the key is of type string and the value is unknown to ts (or similar definitions)
but ANY object should accept date
Need more typescript stuff
Commenting so that youtube recommends more of these type of shorts❤
Great typescript video!
Thanks for teaching me this, although I don't think I will be adopting this pattern. The codebase has to be already be using it
More please. I'm transitioning to Typescript.
don’t
They were not seen again... That's the price of moving to TS.
There's literally no price of moving to TS. That's the great thing about it. Just wirte your js in a .ts file. You'll lose nothing and whatever you can add a type to you reap the benefit. You don't have to go deep into types. You can just minimize the mistakes.
@@j.r.r.tolkien8724 the price is now you use typescript and you have officially adopted the worst implementation of types in any programming language
@@j.r.r.tolkien8724 Yeah + intellisense, your code is eventually more safe logic-wise as well, pretty good for a production environment.
i use the 2nd method cz i can easily understand like writing the object itself
type Param = Record;
Object keys can be a string | number | symbol.
{} is actually pretty powerful when you want to accept any value that isn’t undefined or null. It’s an any, but that any must exist
wouldn't the same apply to the 2 alternate solutions he provided?
You can make your intention more clear by using NonNullable
If you do not want to accept null or undefined then you can configure you typescript's strictNullChecks to true
@@GurjotSingh-no4hxno. Record limits the expectation to an object and not any of the aforementioned primitives
@@alexcoroza4518that’s not the point or intent of what I’m saying
I've been all up in Record in the past months. It seems cleaner to my eyes for some reason than the key index approach (2nd version he showed).
I think something like this in Python wouldn't be a problem since the language clearly distinguishes between "dictionaries" and objects that are "instances of classes"
Also you can still use it, its a great way to tell that something is anything but non nullable
I knew about Record but then I wanted to type an empty object (to fill with keys and value later) and that turned out to be a problem. Using {} works for the moment.
this makes TS A LOT more complex than I thought...
I love the record syntax over the 2nd one
I use the second option. But I've learnt another way. Thanks
Hey thanks , never knew about this
Please stop producing videos with the format of "Stop doing X thing"
Elaborate
@@TheSaintsVEVO Elaborate on what?
Everybody seems to like it tho
Why?
@@pepperdayjackpac4521as it gets more views/ more people are curious
Doing “Record” also works
did you not watch the short?
I use an Interface and mark each things as its type
instance objI {
name: string,
email: string,
image: string,
}
Is this wrong?
yeah. in Angular this is how they type things and it should be on most projects using typescript
@@alexcoroza4518 cheers man, I appreciate your reply.
Using an interface/type/class when you are expecting a specific object type is definitely the best option.
In the rare case that you want to accept any object except a Date, instead of using his solution, I recommend using a conditional type:
function processObjectWithoutDate(obj: T extends Date ? never : T): void {
// Process the object
// ...
}
I'm guilty of doing this. Massive thanks 👍🏾
Actually useful, I could use a longer video, interesting topic.
Can you do a typescript tutorial?
I can recommend Matt Pocock for that.
@@FurryDanOriginal ok thnx do ypu happen to know someone for php. Seems i need to learn it anyway.
@@justindouglas3659 Unfortunately no. Outside of some basics, I never needed PHP nor was interested in it. But by searching for PHP tutorials you surely should find a lot of creators and just stick to the one who seems to flow with your prefered style of learning the best.
@@justindouglas3659 "php for beginners " from laracast channel one of the best php tutorial ever
amazing, thanks!
Great shorts normally but I never bump into this issue, which is confusing as you say "by far the most common issue". If it's being passed like that its normally more defined like as an interface, or as you recommend a type. I never go near the Object type directly.
Yea what's the point of using typescript if you don't want to define what the structure looks like lol
Record
Sure, now try this and see if you can pass a date object:
type Foo = {
bar: string;
}
It will only pass if date has the properties that the object needs. If it doesn't, then it doesn't work, and if it does, great, I won't look for properties other than those necessary. And, for any reason if you need to allow objects of unknown properties then you can just:
type Param = {
[K: PropertyKey]: unknown
};
Cool. I'll go back to writing code that doesn't break because of a lack of knowledge when it comes to data types and how they are used; ergo needing a whole other language just to over-specify my dataums.
object, Record, …And object of ANY form: Record
{} means "anything but a `null` or `undefined`"!
Are you Captain Pike's son ?
Cool, thanks 👌🏾
bro how u so majestic
By far the most common mistake junior devs make is thinking they are smarter than a compiler and throw away readability for pointless char saving ideas. Also doing micro-optimizations on the behalf of readability...
Edit: Just waiting for the smartass to write: "less chars = less file weight and possibly less exec time"... the compiler is there for a reason.
I didn't learn typescript yet , but I can easily understand what did you write, so is it very simple?
Nice tip, but how on earth is this the "most common mistake"?? I've never even come into a situation where I could've done this mistake.
@bronzekoala9141 like he said everything inherits from object so there's a lot of potential reason to pass one around and there's plenty of room for mistakes due to how unintuitive something as abstract as object is
I agree, not a common mistake. I’ve been writing typescript for 10 years. This is a weird niche case where you want strictly compile time type checking for any object except a Date. I say strictly compile time cause you could always use runtime validation for Date very easily which most cases would likely use.
His advice to never use object I find to be questionable advice, and his suggested use of the Record utility type is wrong according to the Typescript team. Record should only be used when you want strictly typed dictionary-like object.
If you want to exclude date just use a conditional type:
function processObjectWithoutDate(obj: T extends Date ? never : T): void {
// Process the object
// ...
}
maybe it's really uncommon, but still the most common lol
Trying to make a react query clone and having a hard time wrapping my head around this concept. I want to easily store state values on any given page. This works to pass unknown state types, but now I'm wondering if there is a way to get full typing from the unknown values down stream? Anyone have any advice on this concept?
What's the name for this? How the folder to put those kind of object factory could be named?
What about nested objects
Which is due to missing tsconfig rules
Let's always do alot of good
everyday I think I get it and then I get proven wrong
I hope JStypes come soon so we can stop with the TS madness.
There is a spec for js comment annotations is the works, but it’s still some that 3rd parties like TS would read for typing.
If you knew the desired members of you Param, why wouldn’t you define a class for it instead? Isn’t that the point of typescript?
I see these videos after I do these mistakes lol. Are you following my code?
You could do that...but...should you?
you can `typeof ` an object or create a class.
At this point you might as well just say `any`
This won't work if you have an object that is declared as an interface.
just dont mix types and interfaces
I haven't seen anyone typing object Object yet
Thankss
Same people that makes fun of Java because « bOiLerPlaTe »
My frustration is anytime I use typescript with a 3rd party library with broken, missing, and overly complicated types. Fighting both Typescript and a new library, is too much. I usually give up and revert to "any."
Why not specifying the fields for the object type?
Or just create an Interface for your models
What do you mean the object works and the date no longer works? I don't see a difference? Where is the actual output of this code?
Just stop using typescript and use an actually typed language
This one doesnt work with interface. I have googled for some solutions, but almost of it are recommended replace type instead or using Record which i see no different from Object/any. Does anyone have another idea!?
You should only use Record utility type when you want a strictly defined dictionary-like object, so his solution is more of a hack.
In his example, it’s a simple case where you want to just exclude the Date type, so using a simple conditional type to exclude Date is the best option:
function processObjectWithoutDate(obj: T extends Date ? never : T): void {
// Process the object
// ...
}
Thanks!
You look like a Meghan Markle copycat
You are very welcome!
What about nested objects?
thats cool
Why `unknown` and not `any`? What's the difference?
That record is the same as Map< String, dynamic> in dart programing, actually for dart to be able to work with Json, it needs to be converted to a Map of Strings keys and dynamic values
If you want a custom type for representing JSON objects in typescript, that provides additional type safety then I recommend the following:
type JSONValue = string | number | boolean | null | JSONValue[] | Record;
I hate typescript so EXTRA
wow, typescript is so complicated and non-intuitive.
But isn't index like a main page?
Awesome
I use lowercase 'object' cuz it's simpler
I think biggest mistakes is not properly setting up a tsconfig.
but {} gives me error every time !!
An object should be an object! What?
why not interface?
Actually the most common would be doing front end dev 😂
Agree 😢😢 especially CSS
Why unknown instead of Any
why not use interface?
What's the difference between using Record & Record ?
Unknown will throw an error until you check the type. Any will disable type checking and you don't have to check the type before using whatever you want
java developers looking at this
Is it possible to have not string keys ?
Yes, you can also use numbers and symbols:
// Using numbers as keys
type NumberRecord = Record;
const numberObject: NumberRecord = {
1: "One",
2: "Two",
3: "Three"
};
// Using symbols as keys
const symbolKey1 = Symbol();
const symbolKey2 = Symbol();
type SymbolRecord = Record;
const symbolObject: SymbolRecord = {
[symbolKey1]: 42,
[symbolKey2]: 99
};
Damn I make this mistake 😂
Cuz in reality you don't want an object you want smth like a dictionary.
Hello Kyle you have been of a great help to me in the last few years as a self-taught developer. Right now I need a job. It has been a real issue for me. I have been a developer of self, building projects for clients as a freelance but I really want to go out of this shell and work in real life company. This is a great problem for me. Please I need your help.
What if {name: string} ?
or just use interfaces?
Why not use an interface ?
An object... That wasn't too hard
hey kyle, whats the difference between unknown vs any?
They are like the exact opposites. Any allows any operation because it could be anything, unknown allows none without narrowing down the type. It’s better to read the documentation and code examples to really get the gist of it
JavaScript has bigger problems than type checking. This is why projects are starting to dump typescript.
I type script but it's a necessary evil I suppose
Typescript generating more bytecode this slows down performance