typescript 如何表达是否存在不应未定义

pgvzfuti  于 2022-12-01  发布在  TypeScript
关注(0)|答案(4)|浏览(126)

如何用 typescript 表达以下内容?

type LanguageName = "javascript" | "typescript" | "java" | "csharp"

type LanguageToWasmMap = {
  [key in LanguageName]: Exclude<LanguageName, key>
}

//I want the below to not throw error
const languageNameToWasmNameMap: LanguageToWasmMap = {
  "javascript" : "typescript"
}

//I want the below to throw error
const languageNameToWasmNameMapWithUndefined: LanguageToWasmMap = {
  "javascript" : undefined
}

typescript 操场:单击此处
进一步考虑,将LanguageToWasmMap设置为Optional是有意义的,因为它意味着什么,并对undefined执行运行时检查。

dzjeubhm

dzjeubhm1#

您可以使用Partial告诉TS不需要所有密钥。

type LanguageName = "javascript" | "typescript" | "java" | "csharp"
    
    type LanguageToWasmMap = {
      [key in LanguageName]: Exclude<LanguageName, key>
    }
    
    //I want the below to not throw error
    const languageNameToWasmNameMap: Partial<LanguageToWasmMap> = {
      "javascript" : "typescript"
    }
    
    //I want the below to throw error
    const languageNameToWasmNameMapWithUndefined: LanguageToWasmMap = {
      "javascript" : undefined
    }

运动场

yhxst69z

yhxst69z2#

您需要将其设置为可选,并在tsconfig中设置exactOptionalPropertyTypes=true,以禁止underfined为可选

type LanguageName = "javascript" | "typescript" | "java" | "csharp"

type LanguageToWasmMap = {
  [key in LanguageName]?: Exclude<LanguageName, key> | never
}

//I want the below to not throw error
const languageNameToWasmNameMap: LanguageToWasmMap = {
  "javascript": "typescript"
}

//I want the below to throw error
const languageNameToWasmNameMapWithUndefined: LanguageToWasmMap = {
  "javascript": undefined
}

Playground

brccelvz

brccelvz3#

使用as似乎可以解决这个问题。不确定这是否有任何意想不到的副作用。

type LanguageName = "javascript" | "typescript" | "java" | "csharp"

type LanguageToWasmMap = {
  [key in LanguageName]: Exclude<LanguageName, key>
}

//I want the below to not throw error
const languageNameToWasmNameMap = {
  "javascript" : "typescript"
} as LanguageToWasmMap

//I want the below to throw error
const languageNameToWasmNameMapWithUndefined = {
  "javascript" : undefined
} as LanguageToWasmMap

Playground

wtlkbnrh

wtlkbnrh4#

我想您可以将类型设置为泛型,但需要指定两次键:

type LanguageName = "javascript" | "typescript" | "java" | "csharp"
    
    type LanguageToWasmMap<K extends LanguageName = LanguageName> = {
      [key in K]: Exclude<LanguageName, key>
    }
    
    //I want the below to not throw error
    const languageNameToWasmNameMap: LanguageToWasmMap<"javascript"> = {
      "javascript" : "typescript"
    }
    
    //I want the below to throw error
    const languageNameToWasmNameMapWithUndefined: LanguageToWasmMap = {
      "javascript" : undefined
    }

播放

相关问题