当前位置:网站首页>Share 16 useful typescript and JS tips

Share 16 useful typescript and JS tips

2022-06-09 20:39:00 Front end talent

english | https://blog.logrocket.com/16-useful-typescript-javascript-shorthands-know/

translate | Yang Xiaoai

JavaScript and TypeScript Technical alternatives that share many useful common code concepts . These code alternatives can help reduce the number of lines of code , This is also our goal .

In this paper , We will share 16 A common TypeScript and JavaScript skill . We will also explore how to use these shorthand examples .

When writing clean and extensible code , Using these techniques is not always the right decision . Clean code is sometimes easier to read and update . Our code must be legible , And communicate meaning and context to other developers , It's also important .

JavaScript All the techniques available in can be found in TypeScript Use the same syntax in . The only slight difference is that TypeScript Type specified in . however ,TypeScript The constructor is abbreviated as TypeScript Unique .

Now? , Let's officially start .

01、 Ternary operator

The ternary operator is JavaScript and TypeScript One of the most popular abbreviations in . It replaces the traditional if…else sentence . Its syntax is as follows :

[condition] ? [true result] : [false result]

The following example demonstrates the traditional if...else Statement and its equivalent abbreviation for using ternary operators :

// Longhand

const mark = 80

if (mark >= 65) {
  return "Pass"
} else {
  return "Fail"
}

// Shorthand
const mark = 80

return mark >= 65 ? "Pass" : "Fail"

02、 Short circuit assessment

Replace if...else Another method of statement is to use short circuit evaluation . This technique uses logic OR Operator || When the expected value is false , Assign default values to variables .

The following example demonstrates how to use short circuit assessment :

// Longhand
let str = ''
let finalStr

if (str !== null && str !== undefined && str != '') {
  finalStr = str
} else {
  finalStr = 'default string'
}

// Shorthand
let str = ''
let finalStr = str || 'default string' // 'default string

03、 Null merge operator

Invalid merge operator ?? Similar to short circuit assessment , Because it is used to assign default values to variables . however , The null merge operator uses the default value only if the expected value is also null .

let me put it another way , If the expected value is false but not null , It will not use default values .

Here are two examples of the null merge operator :

// Example 1
// Longhand
let str = ''
let finalStr

if (str !== null && str !== undefined) {
  finalStr = 'default string'
} else {
  finalStr = str
}
// Shorthand
let str = ''
let finaStr = str ?? 'default string' // ''

// Example 2
// Longhand
let num = null
let actualNum

if (num !== null && num !== undefined) {
  actualNum = num
} else {
  actualNum = 0
}
// Shorthand
let num = null
let actualNum = num ?? 0 // 0

04、 Template text

With the help of JavaScript Powerful ES6 characteristic , We can use template text instead of + To connect multiple variables in a string . To use template text , Please wrap the string in `` in , And wrap variables in these strings ${} in .

The following example demonstrates how to use template text to perform string interpolation :

const name = 'Iby'
const hobby = 'to read'

// Longhand
const fullStr = name + ' loves ' + hobby // 'Iby loves to read'

// Shorthand
const fullStr = `${name} loves ${hobby}`

We can also use template text to build multiline strings , Without having to use \n. for example :

// Shorthand
const name = 'Iby'
const hobby = 'to read'
const fullStr = `${name} loves ${hobby}.
She also loves to write!`

05、 Object attribute assignment abbreviation

stay JavaScript and TypeScript in , We can assign attributes to objects in short form by referring to variables in the object literal . So , The variable must be named with the expected key .

See the following object attribute assignment shorthand example :

// Longhand
const obj = {
  x: 1,
  y: 2,
  z: 3
}

// Shorthand
const x = 8
const y = 10
const obj = { x, y }

06、 Optional links

Dot notation allows us to access the key or value of an object . Use optional Links , We can go further , Even if we are not sure if they exist or are set , You can also read keys or values . When the key doesn't exist , The value from the optional link is undefined .

See the following example of optional links :

const obj = {
  x: {
    y: 1,
    z: 2
  },
  others: [
    'test',
    'tested'
  ] 
}

// Longhand
if (obj.hasProperty('others') && others.length >= 2) {
  console.log('2nd value in others: ', obj.others[1])
}

// Shorthand
console.log('2nd value in others: ', obj.others?.[1]) // 'tested'
console.log('3rd value in others: ', obj.others?.[2]) // undefined

07、 Object to deconstruct

In addition to the traditional dot symbol , Another way to read object values is to deconstruct object values into their own variables .

The following example demonstrates how to read the value of an object using traditional point notation , Compare with shorthand methods that use object deconstruction .

const obj = {
  x: {
    y: 1,
    z: 2
  },
  other: 'test string'
}

// Longhand
console.log('Value of z in x: ', obj.x.z)
console.log('Value of other: ', obj.other)

// Shorthand
const {x, other} = obj
const {z} = x

console.log('Value of z in x: ', z)
console.log('Value of other: ', other)

We can also rename variables that are deconstructed from objects . This is an example :

const obj = {x: 1, y: 2}
const {x: myVar} = object

console.log('My renamed variable: ', myVar) // My renamed variable: 1

08、 Extension operator

Extension operator ... Used to access the contents of arrays and objects . We can use extended operators to replace array functions ( Such as concat) And object functions ( Such as object.assign).

Look at the following example , Learn how to use extended operators to replace ordinary arrays and object functions .

// Longhand
const arr = [1, 2, 3]
const biggerArr = [4,5,6].concat(arr)

const smallObj = {x: 1}
const otherObj = object.assign(smallObj, {y: 2})

// Shorthand
const arr = [1, 2, 3]
const biggerArr = [...arr, 4, 5, 6]

const smallObj = {x: 1}
const otherObj = {...smallObj, y: 2}

09、 Object loop

Conventional JavaScript for The loop syntax is as follows :

for (let i = 0; i < x; i++) { … }

We can use this looping syntax to iterate the array by referring to the array length of the iterator .

There are three kinds for Short for circulation , They provide different ways to traverse array objects :

  • for...of Accessing array entries
  • for...in The index used to access the array and the key used on the object literal
  • Array.forEach Use callback functions to perform operations on array elements and their indexes

Please note that Array.forEach Callback has three possible parameters , Call... In the following order :

  • Array elements of the iteration in progress
  • Index of elements
  • A complete copy of the array

The following example demonstrates the use of these object loop shorthand :

// Longhand
const arr = ['Yes', 'No', 'Maybe']

for (let i = 0; i < arr.length; i++) {
  console.log('Here is item: ', arr[i])
}

// Shorthand
for (let str of arr) {
  console.log('Here is item: ', str)
}

arr.forEach((str) => {
  console.log('Here is item: ', str)
})

for (let index in arr) {
  console.log(`Item at index ${index} is ${arr[index]}`)
}

// For object literals
const obj = {a: 1, b: 2, c: 3}

for (let key in obj) {
  console.log(`Value at key ${key} is ${obj[key]}`)
}

10、Array.indexOf Use abbreviations for bitwise operators

We can use Array.indexOf Method to find whether an item exists in the array . If the item exists in the array , Then this method returns the index position of the item , Returns if it does not exist -1.

stay JavaScript in ,0 It's a false value , And less than or greater than 0 The number of is considered true . Usually , That means we need to use if...else Statement to use the returned index to determine whether the item exists .

Use bitwise operators ~ instead of if...else Statement allows us to get greater than or equal to 0 The true value of any value of .

The following example demonstrates the use of bitwise operators instead of if...else Of the statement Array.indexOf shorthand :

const arr = [10, 12, 14, 16]

const realNum = 10
const fakeNum = 20

const realNumIndex = arr.indexOf(realNum)
const noneNumIndex = arr.indexOf(fakeNum)

// Longhand
if (realNumIndex > -1) {
  console.log(realNum, ' exists!')
} else if (realNumIndex === -1) {
  console.log(realNum, ' does not exist!')
}

if (noneNumIndex > -1) {
  console.log(fakeNum, ' exists!')
} else if (noneNumIndex === -1) {
  console.log(fakeNum, ' does not exist!')
}

// Shorthand
console.log(realNum + (~realNumIndex ? ' exists!' : ' does not exist!')
console.log(fakeNum + (~noneNumIndex ? ' exists!' : ' does not exist!')

11、 Use !! Convert value to Boolean

stay JavaScript in , We can use !![variable] Short for converting variables of any type to Boolean values .

View usage !! An example of [ Variable ] Shorthand for converting a value to a Boolean value :

// Longhand
const simpleInt = 3
const intAsBool = Boolean(simpleInt)

// Shorthand
const simpleInt = 3
const intAsBool = !!simpleInt

12、 arrow /lambda Function expression

JavaScript Functions in can be written using arrow function syntax , Instead of explicitly using function Traditional expressions for keywords . The arrow function is similar to... In other languages lambda function .

Take a look at this example of writing a function in abbreviated form using an arrow function expression :

// Longhand
function printStr(str) {
  console.log('This is a string: ', str)
}
printStr('Girl!')

// Shorthand
const printStr = (str) => {
  console.log('This is a string: ', str)
}
printStr('Girl!')

// Shorthand TypeScript (specifying variable type)
const printStr = (str: string) => {
  console.log('This is a string: ', str)
}
printStr('Girl!')

13、 Use the implicit return of the arrow function expression

stay JavaScript in , We usually use return Keyword returns a value from a function . When we define a function using the arrow function syntax , We can exclude curly braces {} To implicitly return a value .

For multiline statements , For example, an expression , We can wrap the return expression in parentheses () in .

The following example demonstrates shorthand code for implicitly returning a value from a function using an arrow function expression :

// Longhand
function capitalize(name) {
  return name.toUpperCase()
}

function add(numA, numB) {
  return numA + numB
}

// Shorthand
const capitalize = (name) => name.toUpperCase()

const add = (numA, numB) => (numA + numB)

// Shorthand TypeScript (specifying variable type)
const capitalize = (name: string) => name.toUpperCase()

const add = (numA: number, numB: number) => (numA + numB)

14、 Bitwise non operator

stay JavaScript in , We usually use built-in Math Object to access mathematical functions and constants . however , Some functions allow us not to reference Math Object to access the function .

for example , Apply bitwise NOT Operator twice ~~ That allows us to get a value Math.floor().

Look at the following example , Learn how to double digit NOT Operator is used as Math.floor() shorthand :

// Longhand
const num = 4.5
const floorNum = Math.floor(num) // 4

// Shorthand
const num = 4.5
const floorNum = ~~num // 4

15、 Shorthand for exponents

Another useful technique is Math.pow() function . Built in Math The alternative to the object is ** Using skills .

The following example demonstrates the abbreviation of this exponential power :

// Longhand
const num = Math.pow(3, 4) // 81

// Shorthand
const num = 3 ** 4 // 81

16、TypeScript Constructor abbreviation

adopt TypeScript The constructor in creates a class and assigns a value to a class attribute . When using this method ,TypeScript Class properties are automatically created and set .

This shorthand is TypeScript Unique , stay JavaScript Not available in class definitions .

Take a look at the following example , have a look TypeScript Shorthand for constructors :

// Longhand
class Person {
  private name: string
  public age: int
  protected hobbies: string[]

  constructor(name: string, age: int, hobbies: string[]) {
    this.name = name
    this.age = age
    this.hobbies = hobbies
  }
}

// Shorthand
class Person {
  constructor(
    private name: string,
    public age: int,
    protected hobbies: string[]
  ) {}
}

summary

These are just some of the most commonly used JavaScript and TypeScript skill . please remember , Using this code is not always the best choice . The most important thing is to write simple and understandable code that other developers can easily read .

If you still have your favorite JavaScript or TypeScript In terms of skill , Please share with us in the comments !

Last , Thanks for reading , Happy programming , If you find it useful , Please remember to share it with your development friends , Maybe it can help him .

原网站

版权声明
本文为[Front end talent]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206092035011466.html