针对类型'undefined'不能用作索引类型和不能索引的数据类型这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展'string|类型的参数undefined'不能分配给类型为'string
针对类型'undefined'不能用作索引类型和不能索引的数据类型这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展'string | 类型的参数undefined' 不能分配给类型为 'string' 的参数 “未定义”类型不能分配给“字符串”类型 问题解决方案、'string' 类型的表达式不能用于在 Typescript 中索引类型 '{}'、'users | 类型的参数undefined' 不能分配给类型为 'users' 的参数 “未定义”类型不能分配给“用户”类型、ios – 不能下标'[(String)]类型的值?’索引类型为’Int’等相关知识,希望可以帮助到你。
本文目录一览:- 类型'undefined'不能用作索引类型(不能索引的数据类型)
- 'string | 类型的参数undefined' 不能分配给类型为 'string' 的参数 “未定义”类型不能分配给“字符串”类型 问题解决方案
- 'string' 类型的表达式不能用于在 Typescript 中索引类型 '{}'
- 'users | 类型的参数undefined' 不能分配给类型为 'users' 的参数 “未定义”类型不能分配给“用户”类型
- ios – 不能下标'[(String)]类型的值?’索引类型为’Int’
类型'undefined'不能用作索引类型(不能索引的数据类型)
我正在使用带有TypeScript教程的WintellectNow React。在第五部分“排序和过滤”中,作者创建了一个具有可选属性的接口,如下所示:
interface IWidgetToolState { filterCol?: WidgetTableCols; filterValue?: string; sortCol?: WidgetTableCols;}
有一个名为WidgetTableCols的枚举,如下所示:
enum WidgetTableCols { None, Name, Color, Size, Quantity, Price,}
在一个函数中,作者获得了枚举的值,如下所示:
const fName: string = WidgetTableCols[this.state.sortCol].toLocaleLowerCase();
在这里,我无法将类型’undefined’用作索引类型。如果我删除?从接口它起作用,但是后来作者创建了另一个函数,该函数仅设置一个状态值,而打字稿说没有设置所有状态属性。
谁能让我知道如何解决这个问题。
提前致谢。
答案1
小编典典编译器只是告诉您this.state.sortCol
可能没有值,因为您已strictNullChecks
启用标志。
您可以先检查它的存在:
const fName = this.state.sortCol != null ? WidgetTableCols[this.state.sortCol].toLocaleLowerCase() : null;
这将消除错误(但是您将需要处理fName
可能为null 的事实)。
您还可以使用Non-
null断言运算符:
const fName: string = WidgetTableCols[this.state.sortCol!].toLocaleLowerCase();
如果您确定它存在。
'string | 类型的参数undefined' 不能分配给类型为 'string' 的参数 “未定义”类型不能分配给“字符串”类型 问题解决方案
const handleChange = React.useCallback((eventKey: eventKey) => {
let property = dict.find(e => e.name === eventKey)?.prop;
changeProp(property); //Getting error here
}
在这里,在您的函数中,当您在 dict 上查找时,您假设 find 函数可以返回一个空值 dict.find(e => e.name === eventKey)?.prop
,
这样 property
可以是 undefined | string
。
尝试以这种方式更新您的函数 dict.find(e => e.name === eventKey)?.prop || ""
,这意味着如果 find 没有返回任何值,而不是 undefined,变量 property
将是 ""
。
Array find 方法从满足条件的数组中返回第一个元素。但是当没有找到匹配的元素时它返回 >>> t.bool().int()
tensor([0,1,1],dtype=torch.int32)
。
这使得 undefined
的返回类型为 find
,即 Your_Element_Type | undefined
对于您的问题(在阅读 string | undefined
的结果后 prop
).
问题
find
要解决此问题,您需要在函数 let property = dict.find((e) => e.name === eventKey)?.prop
// property will either be a string or undefined
changeProp(property);
中接受 string | undefined
,或者提供后备字符串值(空字符串)。
解决方案
提供一个空字符串作为后备值:
changeProp
此外,可以在编辑器中看到类型:
'string' 类型的表达式不能用于在 Typescript 中索引类型 '{}'
如何解决''string'' 类型的表达式不能用于在 Typescript 中索引类型 ''{}''?
我是打字稿的新手。我只是想为我的 firebase 项目编写一些云函数。我的一个要求是将数组转换为对象。我正在尝试这种技术来实现这一目标:
let msg = {
text : ''hi''
time : 123456789
}
let userIds = [''user1'',''user2'']
let updateObj = userIds.reduce((obj,userId) => {
obj[userId + ''/messages''] = msg
return obj
},{})
我希望 updateObj 是:
{
''user1/messages'' : {
''text'' : ''hi''
''time'' : 123456789
}
''user2/messages'' : {
''text'' : ''hi''
''time'' : 123456789
}
}
但我不明白为什么它会给我这个错误:
src/index.ts:47:6 - error TS7053: Element implicitly has an ''any'' type because expression of type ''string'' can''t be used to index type ''{}''.
No index signature with a parameter of type ''string'' was found on type ''{}''.
47 obj[userId + ''/messages''] = msg
解决方法
您有多种方法可以解决此问题。问题是空对象不接受任意键。
第一个选项是将reduce 函数输入为Record<string,typeof msg>
,这将允许您在该对象的任何键下分配msg 值。这将是最简单和最弱的(从类型安全的角度来看)解决方案。
如果您使用较新版本的打字稿并希望强制所有键都采用 {string}\messages 的确切形式,则其他选项是使用模板字符串文字作为键。要实现该类型,将缩减为 Record<``${string}\messages``,typeof msg>
。
第三个选项是最强类型的,您可以通过键入 Record<``${typeof userIds[number]}\messages``,typeof msg>
来强制键与结果中的完全相同。为此,您还需要使用 userIds
指定您的 as const
,因此它的类型将是 [''user1'',''user2'']
而不是 string[]
。
这些解决方案完全适用于您的问题,所以我猜在实际代码中您没有 users 或 msg static。因此,如果用户是从 api 获得的字符串数组,则第二个选项是最好的,如果示例中的 msg 对象可以具有不同的签名,则只需使用该类型,或者如果您想允许任何值,则只需使用 unknown
.
'users | 类型的参数undefined' 不能分配给类型为 'users' 的参数 “未定义”类型不能分配给“用户”类型
如何解决''users | 类型的参数undefined'' 不能分配给类型为 ''users'' 的参数 “未定义”类型不能分配给“用户”类型?
我正在尝试使用 TYPEORM 创建一个 put 方法,但不明白如何修复此错误以及原因。这个请求一个typeof?但我的用户有价值。 (我是新手,当然)。
谁能帮帮我?我该如何解决?
什么时候:
const user: any = await usersRepository.findOne(req.params.id)
所以: 没问题 (为什么)
错误:
{
"resource": "/Users/camargo/Documents/Estudo/nodejs-1/source/server.ts","owner": "typescript","code": "2345","severity": 8,"message": "Argument of type ''users | undefined'' is not assignable to parameter of type ''users''.\n Type ''undefined'' is not assignable to type ''users''.","source": "ts","startLineNumber": 71,"startColumn": 31,"endLineNumber": 71,"endColumn": 35
}
代码
** source/server.ts */
import http from ''http'';
import { connection } from "./connection/connection"
import express,{ Express } from ''express'';
import morgan from ''morgan'';
import routes from ''./routes/posts'';
import cors from "cors";
import { users } from ''./entities/users'';
// Setando rotas express
const router: Express = express();
const app=express()
app.use(cors())
app.use(express.json())
const server=app.listen(3000,()=>{
console.log("Server rodando... 3000....")
})
app.get("/api",(req,res)=>{
res.send("API - Bem Vindo")
})
connection.then(
async connection=>{
console.log("Conectado")
const usersRepository = connection.getRepository(users);
app.get("/api/users/:id",async(req,res)=>{
/* Metodos */
//MetoDO GET
const user = await usersRepository.findOne({where: { id: req.params.id }})
res.json({
message:"success",payload: user
})
})
// MetoDO POST
app.post("/api/users",async (req,res)=>{
console.log("body",req.body)
const user = await usersRepository.create(req.body)
const results = await usersRepository.save(user);
res.json({
message: "success",payload: results
});
})
// MetoDO DELETE
app.delete("/api/users/:id",res)=>{
const user = await usersRepository.delete(req.params.id)
res.json({
message:"success",})
})
//MetoDO PUT
app.put("/api/users/:id",res)=>{
const user = await usersRepository.findOne(req.params.id)
usersRepository.merge(user,req.body);
const result = await usersRepository.save(user);
res.json({
message:"success",payload:result
})
})
}
).catch(error=>{
console.log(error)
})
/** Conexao teste morgan */
router.use(morgan(''dev''));
/** Parse the req */
router.use(express.urlencoded({ extended: false }));
/** Takes care of JSON data */
router.use(express.json());
/** Regras da API*/
router.use((req,res,next) => {
// CORS
res.header(''Access-Control-Allow-Origin'',''*'');
// CORS headers
res.header(''Access-Control-Allow-Headers'',''origin,X-Requested-With,Content-Type,Accept,Authorization'');
// CORS metodos
if (req.method === ''OPTIONS'') {
res.header(''Access-Control-Allow-Methods'',''GET PATCH DELETE POST'');
return res.status(200).json({});
}
next();
});
/** Routes */
router.use(''/'',routes);
/** Error handling */
router.use((req,next) => {
const error = new Error(''not found'');
return res.status(404).json({
message: error.message
});
});
/** Server */
const httpServer = http.createServer(router);
const PORT: any = process.env.PORT ?? 6060;
httpServer.listen(PORT,() => console.log(`Server rodando em ${PORT}`));
解决方法
const user = await usersRepository.findOne(req.params.id) 返回 user 或 undefined 因为不能保证给定 ID 的用户存在。
usersRepository.merge 需要 users
类型,而您提供的是 users|undefined
类型,如果您在 tsconfig.json 中启用了 strictNullChecking
,则它们彼此不兼容
要解决此问题,您必须先对其进行空检查:
const user = await usersRepository.findOne(req.params.id)
if(user) {
usersRepository.merge(user,req.body);
const result = await usersRepository.save(user);
res.json({
message:"success",payload:result
})
}
res.status(404).json({message: "user not found"})
ios – 不能下标'[(String)]类型的值?’索引类型为’Int’
例如,主要类别是食品,娱乐,在餐桌的食品部分,墨西哥食品,亚洲食品等显示在该部分下.
但是,我遇到了这个错误:
Cannot subscript a value of type ‘[(String)]?’ with an index of type ‘Int’
这是我的代码:
var categoryDictionary = [String:[String]](); var categoriesList = ["Food","Entertainment","Recreation","Shopping","Transport","Post Office"] var foodCategories = [String](); var entertainmentCategories = [String](); var recreationCategories = [String](); var shoppingCategories = [String](); var transportCategories = [String](); var lodgingCategories = [String](); var librariesCategories = [String](); var banksCategories = [String](); var postOfficeCategories = [String]();
这里只是一个附加到数组并将“Food”的键值添加到foodCategory数组的示例
func setupCategoryFood() { var asianFood = "Asian Food" var mexicanFood = "Mexican Food" var fastFood = "Fast Food" var MiddleEasternFood = "Middle Eastern Food" foodCategories.append(asianFood); foodCategories.append(mexicanFood); foodCategories.append(fastFood); foodCategories.append(MiddleEasternFood); categoryDictionary["Food"] = foodCategories; }
然后…
func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell") as! UITableViewCell; var sectionTitle = categoriesList[indexPath.section] var sectionArray = categoryDictionary[sectionTitle]; var itemInArray = sectionArray[indexPath.row]; return cell }
当我尝试将变量设置为等于给定indexpath.row中数组内部的项时,我收到错误:
‘Cannot subscript a value of type ‘[(String)]?’ with an index of type ‘Int’
我真的很困惑,为什么这不起作用,所以任何帮助都会很棒.
解决方法
var itemInArray = sectionArray?[indexPath.row]
你的输出将是:
Optional("Asian Food") Optional("Mexican Food") Optional("Fast Food")
如果您不想要可选,那么您可以这样解开:
var itemInArray = sectionArray![indexPath.row]
你的输出将是:
Asian Food Mexican Food Fast Food
今天关于类型'undefined'不能用作索引类型和不能索引的数据类型的介绍到此结束,谢谢您的阅读,有关'string | 类型的参数undefined' 不能分配给类型为 'string' 的参数 “未定义”类型不能分配给“字符串”类型 问题解决方案、'string' 类型的表达式不能用于在 Typescript 中索引类型 '{}'、'users | 类型的参数undefined' 不能分配给类型为 'users' 的参数 “未定义”类型不能分配给“用户”类型、ios – 不能下标'[(String)]类型的值?’索引类型为’Int’等更多相关知识的信息可以在本站进行查询。
本文标签: