Detailed explanation of any and unknown in TS series, examples


foreword

The article in this film is mainly because I don’t know the type when writing ts. It’s easy to think that using any can solve everything, but it’s not good to write like this. So let's summarize and learn today, and it is better to deal with any type of unknown.


1. An example

You may not be able to understand it just by looking at the renderings, so follow along with the code analysis.
insert image description here

2. The purpose of the example

1. Function description

This example mainly realizes the difference between any type and unknown type.

  • Switch input box type
  • Toggle result function accepts parameter type
  • Enter two contents to judge the result type

First of all, you can see that when the type of the input box is selected as text or number , and the function accepts the parameter type as any , there is no error or prompt.
When switching the type to unknown type, you need to add parameter type judgment, otherwise there will be an error message. You can first take a look at the error message of ts itself:
insert image description here
when it means, the parameter type is unknown type, which is an unknown type. If you continue to execute the following code, there may be a risk of error reporting.
So you need to add type judgment in advance.
For example like this:

const concatenateUnknownString = (str1: unknown, str2: unknown) => {
    
    
  if (typeof str1 === 'string' && typeof str2 === 'string') {
    
    
    return str1 + str2;
  } else {
    
    
    return `err type args1${
      
      typeof str1} args2 ${
      
      typeof str2}`;
  }
}

In this way, by clearly judging the parameter type, you can avoid running errors. Guaranteed type safety.

2. The main difference

  1. Any can accept any type of value, and unknown can also accept any type of value, but requires type checking or type assertion before it can be used.
  2. Specifically, any type can be used for any variable or function parameter, which means that the variable or parameter can be any type of value.

The above code shows the type judgment, and the following is the modified type assertion form.

const concatenateUnknownString = (str1: unknown, str2: unknown) => {
    
    
 	return `${
      
      str1} + ${
      
      str2}`
    return str1 as string + str2
    return Number(str1) + Number(str2)
}

3. Code implementation

1. Subject implementation
definition:

const [textStr, setTestStr] = useState("")
const [textType, setTextType] = useState("text")
const [textTypeCheck, setTextTypeCheck] = useState<{
    
     [key: string]: boolean }>({
    
     text: true, number: false })
const [typeTsCheck, setTypeTsCheck] = useState<{
    
     [key: string]: boolean }>({
    
     any: true, unknown: false })
const [inputObj, setInputObj] = useState<inputType>({
    
    
  first: "",
  second: ""
})
const [typeTs, setTypeTs] = useState("any")

The selected state of the radio is defined here, textTypeCheck and textTsCheck control the state of the input box text type and parameter type respectively.
Main logic part:

const tapFn = () => {
    
    
  if (typeTs === "any") {
    
    
    setTestStr(concatenateAnyString(inputObj.first, inputObj.second))
  } else {
    
    
    setTestStr(concatenateUnknownString(inputObj.first, inputObj.second))
  }
}

const onChangeFn = (e: ChangeEvent<HTMLInputElement>) => {
    
    
  setTextTypeCheck((pre) => {
    
    
    for (let item of Object.keys(pre)) {
    
    
      console.log(item)
      pre[item] = false
    }
    return {
    
     ...pre, [e.target.defaultValue]: e.target.checked }
  })
  setTextType(e.target.defaultValue)
}

const onChangeTypeFn = (e: ChangeEvent<HTMLInputElement>) => {
    
    
  setTypeTsCheck((pre) => {
    
    
    for (let item of Object.keys(pre)) {
    
    
      pre[item] = false
    }
    return {
    
     ...pre, [e.target.defaultValue]: e.target.checked }
  })
  setTypeTs(e.target.defaultValue)
}

const onInputFn = (value: string, valueKey: string) => {
    
    
  setInputObj({
    
    
    ...inputObj,
    [valueKey]: textType === 'number' ? +value : value
  })
}

The Result section of the result obtained by the tapFn control value.
onChangeFn and onChangeTypeFn control the radio state.
onInputFn is the input value.


Summarize

So when the type of a variable cannot be determined, the unknown type should be used first, because it can better ensure type safety. The any type should be avoided unless a special case requires it.

Guess you like

Origin blog.csdn.net/qq_43205326/article/details/131166966